iPhone开发笔记二

来源:互联网 发布:淘宝 新店 低价冲信誉 编辑:程序博客网 时间:2024/04/25 20:45

iphone程序中实现截屏的一种方法
在iphone程序中实现截屏的一种方法:
//导入头文件
#import QuartzCore/QuartzCore.h
//将整个self.view大小的图层形式创建一张图片image UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//然后将该图片保存到图片图

UIImageWriteToSavedPhotosAlbum(image,self,nil,nil);

Objective-C 画图
1.颜色和字体
     UIKit提供了UIColor和UIFont类来进行设置颜色和字体,
     UIColor *redColor=【UIColor redColor】;
    【redColor set】;//设置为红色
     UIFont *front=【UIFont systemFontOfSize:14.0】;//获得系统字体
    【myLable setFont:font】;//设置文本对象的字体
 2.drawRect方法
     对于画图,你首先需要重载drawRect方法,然后调用setNeedsDisplay方法让系统画图:
    -(void)drawRect:(CGRect)rect;//在rect指定的区域画图
     -(void)setNeedsDisplay;//让系统调用drawRect画图

延时函数和Timer的使用
延时函数:
[NSThread sleepForTimeInterval:5.0]; //暂停5s.
Timer的使用:
NSTimer *connectionTimer;  //timer对象
//实例化timer
self.connectionTimer=[NSTimerscheduledTimerWithTimeInterval:1.5 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];
//用timer作为延时的一种方法   
do{
[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];
}while(!done); 
//timer调用函数
-(void)timerFired:(NSTimer *)timer{
done =YES;
}

启动界面的制作
iPhone开发实现splash画面非常简单,做一个全屏的欢迎页的图片,把它命名为Default.png,然后放在Xcode工程的Resource里面。
在XXXAppDelegate.m程序中,插入如下代码:
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  //–inserta delay of 5 seconds before the splash screendisappears–
  [NSThread sleepForTimeInterval:5.0];
  //Override point for customization after applicationlaunch.
  //Add the view controller’s view to the window anddisplay.
  [windowaddSubview:viewController.view];
  [windowmakeKeyAndVisible];
  return YES;
}
这样splash页面就停留5秒后,消失了。
关于控制器Controller的思考
iPhone开发中,只有一个窗口,对应的是多个视图,而视图的组织形式各种各样,关键是要靠控制器来组织各个视图的逻辑关系。大体的关系如下:
窗体---主控制器(比如说导航控制器),主控制器在窗体里面,拖动过去即可,在AppDelegate中写相关变量的代码---在主控制器下有别的控制器,比如视图控制器,可以通过interfacebuilder来关联根视图什么的----视图控制器相当于一个根视图,可以调用其他的视图---视图中包含类文件(.h,.m)和图形界面文件(.xib)(两个之间必须关联起来。)
翻页效果
经常看到iPhone的软件向上向下翻页面的效果,其实这个很简单,已经有封装好的相关方法处理。
//首先设置动画的相关参数
[UIView beginAnimations:@"Curl"context:nil];
[UIView setAnimationDuration:1.25]; //时间
[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];//速度
//然后设置动画的动作和目标视图
[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
参数UIViewAnimationTransitionCurlUp代表向上翻页,如果向下的话UIViewAnimationTransitionCurlDown.
forView那把当前的视图传进去。
//最后提交动画
[UIView commitAnimations];

自定义按钮
UIButton *Btn;
CGRect frame;       
 Btn = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; //按钮的类型    
    [Btn setImage:[UIImage imageNamed:@“aaa.png”] forState:UIControlStateNormal];//设置按钮图片  
  Btn.tag = 10; 
   frame.size.width = 59;  //设置按钮的宽度  
  frame.size.height = 59;   //设置按钮的高度      
  frame.origin.x =150;   //设置按钮的位置     
   frame.origin.y =260;       
 [Btn setFrame:frame];     
   [Btn setBackgroundColor:[UIColor clearColor]];      
    [Btn addTarget:self action:@selector(btnPressed:)forControlEvents:UIControlEventTouchUpInside];   //按钮的单击事件     
   [self.view addSubview:Btn];      
    [Btn release];
-(void)btnPressed:(id)sender {
    //在这里实现按钮的单击事件
}
截取屏幕图片
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400));
//renderInContext 呈现接受者及其子范围到指定的上下文
[self.view.layerrenderInContext:UIGraphicsGetCurrentContext()];
 //返回一个基于当前图形上下文的图片
 UIImage *aImage =UIGraphicsGetImageFromCurrentImageContext();
 //移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();
//以png格式返回指定图片的数据
imageData = UIImagePNGRepresentation(aImage);

使用NSTimer与iphone的简单动画,实现飘雪效果
使用NSTimer与iphone的简单动画,实现飘雪效果,这理原理比较简单,就是定时生成一定的雪花图片,然后使用动画的方式向下漂落(我在其它论坛,看到使用path的方式实现的一个云漂来漂去的效果,实际也可以用那种方式实现,这实际就是前面说的动画效果的两种应用)。所以,我们可以在 viewDidLoad事件中,增加一个图片及定时器并启动,这里的pic请在头文件中定义。
-(void)viewDidLoad{
 [super viewDidLoad];
 self.pic = [UIImage imageNamed:@"snow.png"];//初始化图片
 //启动定时器,实现飘雪效果
 [NSTimer scheduledTimerWithTimeInterval:(0.2) target:self selector:@selector(ontime) userInfo:nil repeats:YES];
}
然后再实现定时器定时调用的ontime方法:
-(void)ontime{
 UIImageView *view = [[UIImageView alloc] initWithImage:pic];//声明一个UIImageView对象,用来添加图片
 view.alpha = 0.5;//设置该view的alpha为0.5,半透明的
 int x = round(random()%320);//随机得到该图片的x坐标
 int y = round(random()%320);//这个是该图片移动的最后坐标x轴的
 int s = round(random()%15)+10;//这个是定义雪花图片的大小
 int sp = 1/round(random()%100)+1;//这个是速度
 view.frame = CGRectMake(x, -50, s, s);//雪花开始的大小和位置
 [self.view addSubview:view];//添加该view
 [UIView beginAnimations:nil context:view];//开始动画
 [UIView setAnimationDuration:10*sp];//设定速度
 view.frame = CGRectMake(y, 500, s, s);//设定该雪花最后的消失坐标
 [UIView setAnimationDelegate:self];
 [UIView commitAnimations];
}
使用NSTimer实现倒计时
今天在CocoaChina上面看到有人在问倒计时怎么做,记得以前在看Iphone31天的时候做过一个,今天翻出来运行不了了,原因是我的IphoneSDK升级到3.1了,以前使用的是2.2.1,在2.2.1里面是可以使用NSCalendarDate的,但是在3.1里面不能够使用,怎么办,只好用NSTimer了,最后还是给实现了。代码也比较简单,开始运行viewDidLoad的时候加载 [NSTimerscheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(timerFireMethod:) userInfo:nilrepeats:YES];//使用timer定时,每秒触发一次
,然后就是写selector了。
-(void)timerFireMethod:(NSTimer*)theTimer
{
 //NSDateFormatter *dateformatter =[[[NSDateFormatter alloc]init]autorelease];//定义NSDateFormatter用来显示格式
 //[dateformatter setDateFormat:@"yyyy MM dd hh mmss"];//设定格式
 NSCalendar *cal = [NSCalendarcurrentCalendar];//定义一个NSCalendar对象
 NSDateComponents *shibo = [[NSDateComponentsalloc] init];//初始化目标时间(好像是世博会的日期)
 [shibo setYear:2010];
 [shibo setMonth:5];
 [shibo setDay:1];
 [shibo setHour:8];
 [shibo setMinute:0];
 [shibo setSecond:0];
 
 NSDate *todate = [caldateFromComponents:shibo];//把目标时间装载入date
 [shibo release];
// NSString *ssss = [dateformatterstringFromDate:dd];
// NSLog([NSString stringWithFormat:@"shiboshi:%@",ssss]);
 
 NSDate *today = [NSDate date];//得到当前时间
// NSString *sss = [dateformatterstringFromDate:today];
// NSLog([NSString stringWithFormat:@"xianzaishi:%@",sss]);
 //用来得到具体的时差
 unsigned int unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit;
 NSDateComponents *d = [cal components:unitFlagsfromDate:today toDate:todate options:0];
 lab.text = [NSStringstringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day],[d hour], [d minute], [d second]];
}
这样就实现了倒计时的功能。
Iphone幻灯片效果+背景音乐
今天弄了几张好看的图片,我就摸索着实现了图片的幻灯片效果,这个以前也实现过了,也算是温故知新吧,另外就是使用SoundEngine类实现背景音乐的播放。SoundEngine类可以从[url=read.php?tid-1215.html]http://www.cocoachina.com/bbs/read.php?tid-1215.html[/url]下载到。
代码很简单贴出来,以备不时只需:
-(void)viewDidLoad
{
 array = [[NSMutableArray alloc] init];
 int i = 1;
 for(i;i<=30;i++)
 {
  [array addObject:[UIImageimageNamed:[NSString stringWithFormat:@"%d.jpg",i]]];
 }
 pictures.animationImages = array;
 pictures.animationDuration = 300;//时间间隔
 pictures.animationRepeatCount = 0;//循环播放
 [pictures startAnimating];//开始播放
//播放背景音乐,利用SoundEngine类进行播放
 SoundEngine_SetListenerPosition(0.0, 0.0,1.0);
 SoundEngine_Initialize(44100);
 SoundEngine_LoadBackgroundMusicTrack([[[NSBundlemainBundle] pathForResource:@"win" ofType:@"caf"] UTF8String],true, true);
 SoundEngine_StartBackgroundMusic();
}
用这种方法播放好像挺占用资源的,比较卡,以后再研究研究其它的方法。


















图片:60b45f23g7555941505a5&690.png 
NSTimer的用法
iPhone为我们提供了一个很强大得时间定时器 NSTimer,它可以完成任何定时功能:
我们使用起来也很简单,只要记住三要素就可以,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理delegate和事件处理方法@selector();
就可以用
1 +(NSTimer *)scheduledTimerWithTimeIn
2 terval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; 
[/pre]来初始化一个 时间定时器
下面我写了一个很简单得例子:
-(void)initTimer
 {
//时间间隔4 NSTimeInterval timeInterval =1.0;
 //定时器6 NSTimer   showTimer =[NSTimer scheduledTimerWithTimeInterval:maxShowTime 
target:self
selector:@selector(handleMaxShowTimer:)
userInfo:nil
 repeats:NO];
}
//触发事件13 -(void)handleMaxShowTimer:(NSTimer *)theTimer
 {
NSDateFormatter dateFormator =[[NSDateFormatter alloc] init];
 dateFormator.dateFormat =@"yyyy-MM-dd  HH:mm:ss";
 NSString *date =[dateformater stringFromDate:[NSDate date]];
 if([date isEqualToString:@"2010-11-09 23:59:59"])
 {
 UIAlertView *alert =[[UIAlertView alloc] initWithTitle:TITLE_NAME
message:@"现在马上就有新的一天了!"22 delegate:self
 cancelButtonTitle:nil
 otherButtonTitles:CONFIRM_TITLE, nil];
 [alert show];
[alert release];
}
[data release];
 [dateFormator release];
 }
iphone开发之 - 启动页面设置
         不管是开发个人项目还是公司项目,大家通常都有一个需求,就是,在app启动的时候,指定一定的时间来显示自己的或者公司的logo,那么,我就将刚刚写好的启动加载页面设置代码贡献出来。(不对指出请留言,好的话也给我留个言吧,鼓励下我!呵呵)
        这里我需要用到NSTimer这个东西,相关的内容可以查看API,有比较详细的解释。
          新建一个项目,随便是什么项目,我建立的是“view based application”,然后,命名为“Logo”,然后确定。
          直接编辑“Resources"目录下的"LogoViewController.xib”。将背景颜色改称绿色,主要是为了当从logo页跳转过来的时候能有感觉到变化。
          然后新建一个NSTimer.

logoviewcon*lo = [[logoviewconalloc] initWithNibName:@"logoviewcon"bundle:nil];
self.logo = lo;
[lo release];
[windowaddSubview:self.logo.view];
//初始化timmer
NSTimer*timer =  [NSTimerscheduledTimerWithTimeInterval: 1.5target: selfselector: @selector(logo:) userInfo: nilrepeats: YES];
注意,初始化的代码中有这么一段:@selector(logo:),其中的方法就是当这个1.5秒时间过去之后自动调用的方法。
-(void) logo:(NSTimer*)timer{
[logo.view removeFromSuperview];
[timer invalidate];//这句代码用来终止timmer,否则,每过1.5秒,就会执行该方法一次,我们是要在开始的时候执行一次就够了。
}
iphone 学习笔记

1。隐藏状态栏[[UIApplication sharedApplication] setStatusBarHidden:YES];

/******************************************************************************
1、取随机数:
NSData *datanow = [NSData data];       
int i = (int)datanow;               
srand(i);                              
rand();
//int effectPicNum = rand()%7;
******************************************************************************/
/******************************************************************************
2、播放音乐:
-(void) playMusic
{
@try{
//取文件路径
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"startLogo" ofType:@"mp3"];       
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];  
musicPlayer= [[AVAudioPlayeralloc] initWithContentsOfURL:musicURL error:nil];
[musicURL release];
//[musicPlayer prepareToPlay];
//[musicPlayer setVolume:1];            //设置音量大小
musicPlayer.numberOfLoops= 0; //设置播放次数,-1为一直循环,0为一次
[musicPlayerplay]; 
}
@catch(NSException* e) {
}

******************************************************************************/
/******************************************************************************
3、每隔0.8秒执行timeCount方法:
NSTimer*countTimer;
countTimer= [NSTimerscheduledTimerWithTimeInterval: 0.8target: selfselector: @selector(timeCount:)  userInfo: nilrepeats: YES];   
[countTimerfire];     //执行timer
******************************************************************************/
/******************************************************************************
4、延迟1秒执行test方法:
[selfperformSelector:@selector(test) withObject:nilafterDelay:0.1];
******************************************************************************/
/******************************************************************************
5、启动线程:
[NSThreaddetachNewThreadSelector:@selector(transImage) toTarget:selfwithObject:nil]; 
timer=[NSTimerscheduledTimerWithTimeInterval:0.03target:selfselector:@selector(TimerClock:) userInfo:nilrepeats:YES]; //启动一个NSTimer执行广播
[timerfire];  //执行timer

-(void)TimerClock:(id)sender
{
//控制延迟触发
if(Timecontrol>1) {   
[timerConditionbroadcast];      //广播,触发处于等待状态的timerCondition

}

-(void)transImage

isRunning=YES;
while (countTime < COUNTTIME) {
[timerConditionwait];
lim += 255 / (2 * KFrame);
[selfprocessImage];
countTime += 1000 / KFrame;
}
[timerinvalidate];
isRunning=NO;
}
******************************************************************************/
/******************************************************************************
6、获取文件路径:
//通过NSHomeDirectory获得文件路径
NSString *homeDirectory = NSHomeDirectory();
NSString *fileDirectory = [homeDirectory stringByAppendingPathComponent:@"temp/app_data.plist"];

//使用NSSearchPathForDirectoriesInDomains检索指定路径
NSArray*path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//常量NSDocumentDirectory表示正在查找Documents目录的路径(使用NSCachesDirectory表明要查找的时Caches文件夹),常量NSUserDomainMask表明我们希望将搜索限制于我们应用程序的沙盒,最后一个参数决定了是否“展开”波浪线符号。
//在Mac系统中,‘~’表示主路经(Home),如果不展开,路径看起来就是:‘~/Documents’,展开后即得到完整路径。这个参数一直设置位真即可。
NSString *documentsDirectory = [paths objectAtIndex:0];z
NSString *fileDirectory = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

//使用Foundation中的NSTemporaryDirectory函数直接返回代表temp文件夹的全路径的字符串对象
NSString *tempDirectory = NSTemporaryDirectory();
NSString*file = [tempDirectory stringByAppendingPathComponent:@"file.txt"];


  Example:
NSArray*path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);
NSString *docDir = [path objectAtIndex:0];
NSLog(@"filepath:%@",docDir);
NSString*str = @"hello.jpg";
NSString*filepath = [docDir stringByAppendingPathComponent:str];
//NSString *filepath = [docDir stringByAppendingPathComponent:[NSString stringWithUTF8String:"///mest.txt"]];
NSLog(@"filepath:%@",filepath);
BOOLsuccess = [[NSFileManagerdefaultManager]createFileAtPath: filepath contents:nilattributes:nil];
NSLog(@"result",success);
printf("Create File:%s %s.",[filepath UTF8String], success ? "Success": "Error");

NSString* reValue= [NSString stringWithString:@"\"success\""];
NSLog(reValue);
******************************************************************************/
/************************************************************************************************************************************************************
7文件、文件夹操作
//如果"/Documents/Theme"路径不存在,则创建。
if(![[NSFileManagerdefaultManager]fileExistsAtPath:themePath])
{
[[NSFileManagerdefaultManager] createDirectoryAtPath:themePath attributes:nil];
}
//删除已存在的同名文件夹
if([[NSFileManagerdefaultManager] fileExistsAtPath:savePath]) {
[[NSFileManagerdefaultManager] removeItemAtPath:savePath error:NULL];
}
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
7 子线程抛给主线程:
[selfperformSelectorOnMainThread:@selector(shiftView) withObject:nilwaitUntilDone:YES];

************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
8获取当前时间
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];

//获取当前时间作为productId
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"hhmmss"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
downloadInfo.productId = locationString;
[formatter release];
/******************************************************************************
 函数名称  : getDate
函数描述  : 获取当前日期时间
 输入参数  : N/A
 输出参数  : N/A
 返回值    : NSString 当前时间
 备注     :
 ******************************************************************************/
-(NSString *)getDate
{
NSDateFormatter*formatter = [[NSDateFormatteralloc] init];
[formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"];
NSString *locationString=[formatter stringFromDate: [NSDate date]];
[formatter release];
return locationString;
}
大写的H日期格式将默认为24小时制,小写的h日期格式将默认为12小时
不需要特别设置,只需要在dataFormat里设置类似"yyyy-MMM-dd"这样的格式就可以了
日期格式如下:
y  年  Year  1996; 96  
M  年中的月份  Month  July; Jul; 07  
w  年中的周数  Number  27  
W  月份中的周数  Number  2  
D  年中的天数  Number  189  
d  月份中的天数  Number  10  
F  月份中的星期  Number  2  
E  星期中的天数  Text  Tuesday; Tue  
a  Am/pm 标记  Text  PM  
H  一天中的小时数(0-23)  Number  0  
k  一天中的小时数(1-24)  Number  24  
K  am/pm 中的小时数(0-11)  Number  0  
h  am/pm 中的小时数(1-12)  Number  12  
m  小时中的分钟数  Number  30  
s  分钟中的秒数  Number  55  
S  毫秒数  Number  978  
z  时区  General time zone  Pacific Standard Time; PST; GMT-08:00  
Z  时区  RFC 822 time zone  -0800
************************************************************************************************************************************************************/
/************************************************************************************************************************************************************
读取和写入plist文件

plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法: 以下代码在Mac和iPhone中均适用。 
写入plist文件: NSMutableDictionary * dict = [ [ NSMutableDictionary alloc ] initWith 
  
plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法:    
   
以下代码在Mac和iPhone中均适用。
   
写入plist文件:  
NSMutableDictionary* dict = [ [ NSMutableDictionaryalloc ] initWithContentsOfFile:@"/Sample.plist"];
[ dict setObject:@"Yes"forKey:@"RestartSpringBoard"];
[ dict writeToFile:@"/Sample.plist"atomically:YES];
   
读取plist文件:
   
NSMutableDictionary* dict =  [ [ NSMutableDictionaryalloc ] initWithContentsOfFile:@"/Sample.plist"];
NSString* object = [ dict objectForKey:@"RestartSpringBoard" ];
************************************************************************************************************************************************************/
 UIView翻转效果实现


新建一个view-based模板工程,在ViewController文件中添加下面的代码,即可实现翻转效果;

- (void)viewDidLoad {
     [super viewDidLoad];
//需要翻转的视图

UIView *parentView = [[UIView alloc] initWithFrame:CGRectMake(0, 150, 320, 200)];
parentView.backgroundColor = [UIColor yellowColor];
parentView.tag = 1000;

[self.view addSubview:parentView];
}

//需要在h头文件声明下面的动作响应函数
//在xib文件中添加一个button,其响应函数为下面的函数
//运行程序后,点击button就看到翻转效果
-(IBAction)ActionFanzhuan{


//获取当前画图的设备上下文
CGContextRef context = UIGraphicsGetCurrentContext();

//开始准备动画
[UIView beginAnimations:nil context:context];

//设置动画曲线,翻译不准,见苹果官方文档 
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

//设置动画持续时间
[UIView setAnimationDuration:1.0];



//因为没给viewController类添加成员变量,所以用下面方法得到viewDidLoad添加的子视图
UIView *parentView = [self.view viewWithTag:1000];

//设置动画效果

[UIView setAnimationTransition: UIViewAnimationTransitionCurlDown forView:parentView cache:YES];  //从上向下
// [UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:parentView cache:YES];   //从下向上
// [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:parentView cache:YES];  //从左向右
// [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:parentView cache:YES];//从右向左


//设置动画委托

[UIView setAnimationDelegate:self];

//当动画执行结束,执行animationFinished方法
[UIView setAnimationDidStopSelector:@selector(animationFinished:)];

//提交动画
[UIView commitAnimations];

}

//动画效果执行完毕
- (void) animationFinished: (id) sender{
NSLog(@"animationFinished !");
}

运行程序,点击按钮,就能看到动画效果了
iPhone 实现动画效果
iPhone中实现动画,主要有两种方式:UIView的动画块和Core Animation的CATransition类。

1、UIView的动画块 
之所以称为动画块,是因为UView动画是成块运行的,也就是说作为完整的事务一次性运行。
beginAnimation:context:标志动画块开始;
commitAnimations标志动画块结束。(这个commit多少已经暗示这个操作是事务性的)
这里面通常涉及4个操作:
beginAnimation:context:标志动画块开始
setAnimationCurve:定义动画加速或减速的方式,有四种,ease-in/ease-out,ease-in,linear,ease-out
setAnimationDuration:定义动画持续时间(以秒为单位)
commitAnimations:标志动画块结束
所有这些操作都是针对UIView的,或者说是UIView的类函数。
给段代码示例:
    1.    CGContextRef context = UIGraphicsGetCurrentContext();[UIView beginAnimations:nil context:context];[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];[UIView setAnimationDuration:2.0f];[UIView setAnimationBeginsFromCurrentState:YES];[UIView setAnimationDelegate:self];[UIView setAnimationDidStopSelector:@selector(animationFinished:)];[self.imageView setTransform:CGAffineTransformMakeScale(0.25f, 0.25f)];[UIView commitAnimations];  
 

        (这里面设置了动画的delegate,在动画结束后执行animationFinished:函数)


UIView除了实现上面这种简单的动画,还支持视图的翻转。例如在上面代码的[UIView commitAnimations]前加上下面这句,便可以实现视图的翻转(翻转后的试图中,imageView的大小变为原来的0.25倍):

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
其中,参数UIViewAnimationTransitionFlipFromLeft定义了翻转的方式。
关于UIView的userInteractionEnabled属性
如果父视图为ParentView包含一个Button,如果再ParentView上添加子视图ChildView,且ChildView盖住了Button,
那么Button就得到不响应了,为了让Button响应,可以设置ChildView的userInteractionEnabled = NO;
最近被这个问题困扰了很久,开始想用事件传递的方法,重写类继承自UIView,最后被这简单属性搞定了....
让一个UIImageView响应点击事件
UIImageView *imgView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320, 44)];
imgView.userInteractionEnabled=YES;
UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:selfaction:@selector(onClickImage)];
[imgView addGestureRecognizer:singleTap];
[singleTap release];
-(void)onClickImage{
   // here, do whatever you wantto do
    NSLog(@"imageview is clicked!");
}
iphone调用系统电话、浏览器、地图、邮件等
openURL的使用方法:
view plaincopy toclipboardprint?
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appString]];  
其中系统的appString有:
view plaincopy toclipboardprint?
1.Map    http://maps.google.com/maps?q=Shanghai  
2.Email  mailto://myname@google.com  
3.Tel    tel://10086  
4.Msg    sms://10086  
openURL能帮助你运行Maps,SMS,Browser,Phone甚至其他的应用程序。这是Iphone开发中我经常需要用到的一段代码,它仅仅只有一行而已。
- (IBAction)openMaps {
    //打开地图 
   NSString*addressText = @"beijing";
    //@"1Infinite Loop, Cupertino, CA 95014"; 
   addressText =[addressTextstringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
   NSString*urlText = [NSStringstringWithFormat:@"http://maps.google.com/maps?q=%@",addressText]; 
   NSLog(@"urlText=============== %@", urlText);
   [[UIApplicationsharedApplication] openURL:[NSURL URLWithString:urlText]];
}

- (IBAction)openEmail {
     //打开mail // Fire off an email to apple support
      [[UIApplication sharedApplication]openURL:[NSURL   URLWithString:@"mailto://devprograms@apple.com"]];
 } 
 
- (IBAction)openPhone {
  
    //拨打电话
    // CallGoogle 411
    [[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"tel://8004664411"]];
 } 
 
- (IBAction)openSms {
    //打开短信
     // Text toGoogle SMS
    [[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"sms://466453"]];
}

-(IBAction)openBrowser {
    //打开浏览器
    // Lanuch any iPhone developers fav site
     [[UIApplication sharedApplication] openURL:[NSURLURLWithString:@"http://itunesconnect.apple.com"]];
 }
iphone程序内调用谷歌地图

使用CLLocationManager类,MKMapView。并且实现<MKMapViewDelegate,CLLocationManagerDelegate>
//初始化CLLocationManager,CLLocationManager获得当前地理坐标
locmanager=[[CLLocationManager alloc]init];

[locmanager setDelegate:self];
 //设置精确度
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];

[locmanagerstartUpdatingLocation];
执行完以后,会自动调用代理方法:

在代理方法:


- (void)locationManager:(CLLocationManager *)managerdidUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation *)oldLocation{
//初始化矩形大小
 CGRect rect=CGRectMake(0,0,320,460);
//设置地图大小为矩形大小
map=[[MKMapView alloc] initWithFrame:rect];

CLLocationCoordinate2Dloc=[newLocation coordinate];
lat=loc.latitude;
lon=loc.longitude;

//coordinate坐标
CLLocationCoordinate2DtheCoordinate;
CLLocationCoordinate2DtheCenter;

//theCoordinate.latitude=lat;
//theCoordinate.longitude=lon;
theCoordinate=loc;
[map setDelegate:self];
//设置地图显示的类型,有卫星地图,道路,等
[map setMapType:MKMapTypeStandard];
//[mapsetMapType:MKMapTypeSatellite];
//区域坐标Region(区域,地域)

MKCoordinateRegiontheRegin;
//theCenter.latitude=lat;
//theCenter.longitude=lon;
theCenter=loc;
theRegin.center=theCenter;

//坐标间距(span:间隔,间距)
MKCoordinateSpantheSpan;

theSpan.latitudeDelta=0.1;
theSpan.longitudeDelta=0.1;
//设置地图显示的区域,
theRegin.span=theSpan;
//[mapsetRegion:theRegin];
[map regionThatFits:theRegin];
map.showsUserLocation=YES;
[self.viewaddSubview:map];

}


- (MKAnnotationView *)mapView:(MKMapView *)mapViewviewForAnnotation:(id<MKAnnotation>)annotation{
NSLog(@"-------viewForAnnotation-------");
//此类可以显示针一样的图标
MKPinAnnotationView*newAnnotation=[[MKPinAnnotationViewalloc] initWithAnnotation:annotationreuseIdentifier:@"annotation1"];

//newAnnotation.animatesDrop=YES;
//newAnnotation.animatesDrop=NO;

newAnnotation.pinColor=MKPinAnnotationColorPurple;
//显示标志提示
newAnnotation.canShowCallout=YES;
return newAnnotation;
}
UIPageControl实现自定义按钮

有时候UIPageControl需要用到白色的背景, 那么会导致上面的点按钮看不见或不清楚,
我们可以通过继承该类重写函数来更换点按钮的图片现实.
实现思路如下.
新建类继承UIPageControl :
@interface MyPageControl : UIPageControl
{
    UIImage*imagePageStateNormal;
    UIImage*imagePageStateHighlighted;
}
- (id)initWithFrame:(CGRect)frame;
@property (nonatomic, retain) UIImage*imagePageStateNormal;
@property (nonatomic, retain) UIImage*imagePageStateHighlighted;
@end

声明了初始化该类的函数
用了两个UIImage保存两张图片, 大家知道的, UIPageCotrol的按钮分为两态, 一个是正常, 一个是高亮
接下来实现该类以及重写父类方法:
@interfaceMyPageControl(private)  // 声明一个私有方法, 该方法不允许对象直接使用
- (void)updateDots;
@end

@implementation MyPageControl  //实现部分

@synthesize imagePageStateNormal;
@synthesize imagePageStateHighlighted;

- (id)initWithFrame:(CGRect)frame { // 初始化
    self = [superinitWithFrame:frame];
    return self;
}

- (void)setImagePageStateNormal:(UIImage*)image {  // 设置正常状态点按钮的图片
    [imagePageStateNormalrelease];
    imagePageStateNormal= [image retain];
    [self updateDots];
}

-(void)setImagePageStateHighlighted:(UIImage *)image { // 设置高亮状态点按钮图片
    [imagePageStateHighlightedrelease];
    imagePageStateHighlighted= [image retain];
    [self updateDots];
}

- (void)endTrackingWithTouch:(UITouch*)touch withEvent:(UIEvent *)event { // 点击事件
    [superendTrackingWithTouch:touch withEvent:event];
    [self updateDots];
}

- (void)updateDots { // 更新显示所有的点按钮
    if(imagePageStateNormal || imagePageStateHighlighted)
    {
        NSArray*subview = self.subviews;  // 获取所有子视图
        for(NSInteger i = 0; i < [subview count]; i++)
        {
            UIImageView*dot = [subview objectAtIndex:i];  // 以下不解释, 看了基本明白
            dot.image= self.currentPage == i ? imagePageStateNormal : imagePageStateHighlighted;
        }
    }
}

- (void)dealloc { // 释放内存
    [imagePageStateNormalrelease], imagePageStateNormal = nil;
    [imagePageStateHighlightedrelease], imagePageStateHighlighted = nil;
    [super dealloc];
}

@end
OK, 在添加处加入以下来实例化该对象代码:
MyPageControl *pageControl =[[MyPageControl alloc] initWithFrame:CGRectMake(0,0, 200, 30)];
pageControl.backgroundColor = [UIColorclearColor];
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[pageControlsetImagePageStateNormal:[UIImageimageNamed:@"pageControlStateNormal.png"]];
[pageControl setImagePageStateHighlighted:[UIImageimageNamed:@"pageControlStateHighlighted.png"]];
[self.view addSubview:pageControl];
[pageControl release];
iPhone电子书toolbar的实现
iPhone电子书的toolbar一般都设计成半透明,上面放置一个进度条和一个Label(用于显示页码),这里用代码做一个最基本的实现。
生成一个UIToolbar
UIToolbar *toolbar =[[[UIToolbar alloc] init] autorelease];
toolbar.barStyle=UIBarStyleBlackTranslucent;
[toolbar sizeToFit];
CGFloat toolbarHeight =[toolbar frame].size.height;
CGRect rootViewBounds =self.parentViewController.view.bounds;
CGFloat rootViewHeight =CGRectGetHeight(rootViewBounds);
CGFloat rootViewWidth =CGRectGetWidth(rootViewBounds);
CGRect rectArea = CGRectMake(0, rootViewHeight-toolbarHeight,rootViewWidth, toolbarHeight);
[toolbar setFrame:rectArea];
toolbar.backgroundColor= [UIColor clearColor];
生成一个Slider

UISlider*readSlider =[[[UISlideralloc]initWithFrame:CGRectMake(0,0, 225,30)] autorelease];
readSlider.minimumValue = 0.0f;
readSlider.maximumValue = 1.0f;
readSlider.continuous = YES;
readSlider.enabled = YES;
生成一个Label

UILabel*readLabel =[[[UILabelalloc]initWithFrame:CGRectMake(230,0, 50,30)] autorelease];
readLabel.backgroundColor = [UIColor clearColor];
readLabel.textColor =[UIColor whiteColor];
Slider和Label加入到toolbar中

NSMutableArray *tbitems =[NSMutableArray array];
[tbitems addObject:[[[UIBarButtonItem alloc]initWithCustomView:readSlider] autorelease]];
[tbitems addObject:[[[UIBarButtonItemalloc] initWithCustomView:readLabel]autorelease]]; 
toolbar.items = tbitems;
toolbar加入到当前view中 
[self.navigationController.view addSubview:toolbar];
点击屏幕即隐藏的功能,将toolbar的hidden属性置为YES即可

toolBar.hidden = YES;
 
UIView中bounds和frame的差别?
翻译文档上的
bounds是指这个view在它自己坐标系的坐标和大小 而frame指的是这个view在它superview的坐标系的坐标和大小
区别主要在坐标系这一块。

很明显一个是自己为原点的坐标系,一个是以屏幕为原点的坐标系。绝对坐标。。。相对坐标。。。比如屏幕旋转的时候就要以相对来重绘。 
frame 如果一个按钮,是在表格里,按钮的frame 的坐标也是相对的,并不是相对屏幕,也就是说是相对坐标,不是绝对坐标

我也想知道任何一个uiview如何求得它在屏幕上的坐标。

view 的frame是view在它的super view 的位置与尺寸。
view 的bounds可以用来帮助它的subview来定位的 ,layoutSubviews。

Frame  is  in  terms  of  superview's  coordinate  system   

框架是从父视图的坐标系统


Bounds   is  in  terms  of   local  coordinate  system
是在局部坐标系统

[ 此帖被haoxue在2011-11-26 16:07重新编辑 ]
图片:6_491_772cfea14e61028.png 
很明显,bounds的原点是(0,0)点,而frame的原点却是任意的。
frame 如果一个按钮,是在表格里,按钮的frame 的坐标也是相对的,并不是相对屏幕,也就是说是相对坐标,不是绝对坐标。
frame 是相对坐标。bounds是绝对坐标。
Android的开发过程中,绝对坐标,这样画出来的位置都是相对于屏幕的而不是相对于控件的

 什么是绝对坐标值,相对坐标值?
绝对坐标是:X,Y    就是相对于坐标原点的。                    
例如(15,20)相对坐标是:@X,Y   就是相对于参考点(可以是自己设定的一个点)。                  
   例如(15,20)相对于参考点(1,1)的坐标,表示:@14,19                            
(15,20)相对于参考点(-1,-1)的坐标,表示:@16,21
bounds是指这个view在它自己坐标系的坐标和大小 而frame指的是这个view在它superview的坐标系的坐标和大小.
区别主要在坐标系这一块。
很明显一个是自己为原点的坐标系,一个是以屏幕为原点的坐标系。
[ 此帖被haoxue在2011-11-26 16:12重新编辑 ]
图片:frame_bounds_rects.jpg 
多使用宏定义常量。tag,frame大小,一些判断标志位。
#define kIndexValueTag 1

苹果屏幕截图快捷键

一般在Mac上用Command-Shif-3/4来截图。注:Command=苹果键 其实还有几个辅助键,来起到不同的截图功能……
011)Command-Shift-3(适用于OS9,10.1X和10.2)
02将整个屏幕拍下并保存到桌面。
032)Command-Shift-4(适用于OS9,10.1X和10.2)
04将屏幕的一部分拍下并保存到桌面。当按下着几个键后,光标会变为一个十字,可以拖拉来选取拍报区域。
053)Command-Shift-Control-3(适用于OS9和10.2)
06将整个屏幕拍下并保存到剪贴板,可以Command+V直接粘贴到如Photoshop等软件中编辑。
074)Command-Shift-Control-4(适用于OS9和10.2)
08将屏幕的一部分拍下并保存到剪贴板。
095)Command-Shift-4再按空格键(适用于10.2)
10光标会变成一个照相机,点击可拍下当前窗口或菜单或Dock以及图标等,只要将照相机移动到不用区域(有效区域会显示为浅蓝色)点击。
116)Command-Shift-Control-4再按空格键(适用于10.2)
12将选取的窗口或其他区域的快照保存到剪贴板。
137)Command-Shift-Capslock-4(适用于OS9)
14将当前的窗口拍下并保存到桌面。
158)Command-Shift-Capslock-Control-4(适用于OS9)
16将当前的窗口拍下并保存到剪贴板。设置透明度



1[myView setAlpha:value];   (0.0 < value < 1.0)


设置背景色
1[myView setBackgroundColor:[UIColor redColor]];
2(blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;
3orangeColor;purpleColor;brownColor; clearColor; )


自定义颜色:
1UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)];      0.0~1.0


宽度和高度
1768X1024     1024X768    状态栏高 20 像素高   导航栏 工具栏 44像素高


隐藏状态栏:
1[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]iOS开发_iphone开发_iphone界面如何实现下拉列表


    
代码如下:
     
    #import <UIKit/UIKit.h>
    @interface DropDownList : UIView<UITableViewDelegate,UITableViewDataSource> {
    UITextField* textField;   //文本输入框
    NSArray* list;            //下拉列表数据
    BOOL showList;             //是否弹出下拉列表
    UITableView* listView;    //下拉列表
    CGRect oldFrame,newFrame;   //整个控件(包括下拉前和下拉后)的矩形
    UIColor *lineColor,*listBgColor;//下拉框的边框色、背景色
    CGFloat lineWidth;               //下拉框边框粗细
    UITextBorderStyle borderStyle;   //文本框边框style
    }
    @property (nonatomic,retain)UITextField *textField;
    @property (nonatomic,retain)NSArray* list;
    @property (nonatomic,retain)UITableView* listView;
    @property (nonatomic,retain)UIColor *lineColor,*listBgColor;
    @property (nonatomic,assign)UITextBorderStyle borderStyle;
    -(void)drawView;
    -(void)setShowList:(BOOL)b;
    @end
    #import "DropDownList.h"
    @implementation DropDownList
    @synthesize textField,list,listView,lineColor,listBgColor,borderStyle;
    - (id)initWithFrame:(CGRect)frame {
     
    if(self=[super initWithFrame:frame]){
    //默认的下拉列表中的数据
    list=[[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",nil];
     
    borderStyle=UITextBorderStyleRoundedRect;
     
    showList=NO; //默认不显示下拉框
    oldFrame=frame; //未下拉时控件初始大小
    //当下拉框显示时,计算出控件的大小。
    newFrame=CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height*5);
     
    lineColor=[UIColor lightGrayColor];//默认列表边框线为灰色
    listBgColor=[UIColor whiteColor];//默认列表框背景色为白色
    lineWidth=1;     //默认列表边框粗细为1
     
    //把背景色设置为透明色,否则会有一个黑色的边
    self.backgroundColor=[UIColor clearColor];
    [self drawView];//调用方法,绘制控件
     
    }
    return self;
    }
    -(void)drawView{
    //文本框
    textField=[[UITextField alloc]
      initWithFrame:CGRectMake(0, 0,
    oldFrame.size.width, 
    oldFrame.size.height)];
    textField.borderStyle=borderStyle;//设置文本框的边框风格
    [self addSubview:textField];
        [textField addTarget:self action:@selector(dropdown) forControlEvents:UIControlEventAllTouchEvents]; 
     
    //下拉列表
    listView=[[UITableView alloc]initWithFrame:
      CGRectMake(lineWidth,oldFrame.size.height+lineWidth, 
    oldFrame.size.width-lineWidth*2,
    oldFrame.size.height*4-lineWidth*2)];
    listView.dataSource=self;
    listView.delegate=self;
    listView.backgroundColor=listBgColor;
    listView.separatorColor=lineColor;
    listView.hidden=!showList;//一开始listView是隐藏的,此后根据showList的值显示或隐藏
     
    [self addSubview:listView]; 
    [listView release];
    }
    -(void)dropdown{
    [textField resignFirstResponder];
    if (showList) {//如果下拉框已显示,什么都不做
    return;
    }else {//如果下拉框尚未显示,则进行显示
    //把dropdownList放到前面,防止下拉框被别的控件遮住
     
    [self.superview bringSubviewToFront:self];
    [self setShowList:YES];//显示下拉框
    }
    }
    #pragma mark listViewdataSource method and delegate method
    -(NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
    return list.count;
    }
    -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellid=@"listviewid";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:cellid];
    if(cell==nil){
    cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
      reuseIdentifier:cellid]autorelease];
    }
    //文本标签
    cell.textLabel.text=(NSString*)[list objectAtIndex:indexPath.row];
    cell.textLabel.font=textField.font;
     
    cell.selectionStyle=UITableViewCellSelectionStyleGray;
    return cell;
    }
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return oldFrame.size.height;
    }
    //当选择下拉列表中的一行时,设置文本框中的值,隐藏下拉列表
    -(void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSLog(@"select");
    textField.text=(NSString*)[list objectAtIndex:indexPath.row];
    //NSLog(@"textField.text=%@",textField.text);
    [self setShowList:NO];
    }
    -(BOOL)showList{//setShowList:No为隐藏,setShowList:Yes为显示
    return showList;
    }
    -(void)setShowList:(BOOL)b{
    showList=b;
    NSLog(@"showlist is set ");
    if(showList){
    self.frame=newFrame;
    }else {
    self.frame=oldFrame;
    }
    listView.hidden=!b;
    }
    /*
     
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect {
        // Drawing code.
    }
    */
    - (void)dealloc {
        [super dealloc];
    }
    @end
create toolbar using new
  toolbar = [UIToolbar new];
  toolbar.barStyle = UIBarStyleDefault;
  [toolbar sizeToFit];
  toolbar.frame = CGRectMake(0, 410, 320, 50);
 
 
iphone之UISegmentedControl


代码:
 
//选择按钮
  NSArray*buttonNames = [NSArray arrayWithObjects:@"今天", @"本周", @"本月",nil];
  UISegmentedControl* segmentedControl = [[UISegmentedControl alloc]initWithItems:buttonNames];
  [segmentedControl setFrame:CGRectMake(60, 10, 200, 40)];
  segmentedControl.selectedSegmentIndex=1;
  //添加事件
  [segmentedControl addTarget:self action:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];
  [self.viewaddSubview:segmentedControl];
  [segmentedControl release];

//事件

-(void)segmentAction:(UISegmentedControl *)Seg{
  NSIntegerIndex = Seg.selectedSegmentIndex;
  NSLog(@"Seg.selectedSegmentIndex:%d",Index);
}


图片:4adf31eat76b2e24823fb&690.png 
 

iOS Programming – 触摸事件处理

iphone/ipad无键盘的设计是为屏幕争取更多的显示空间,大屏幕在观看图片、文字、视频等方面为用户带来了更好的用户体验。而触摸屏幕是iOS设备接受用户输入的主要方式,包括单击、双击、拨动以及多点触摸等,这些操作都会产生触摸事件。

在Cocoa中,代表触摸对象的类是UITouch。当用户触摸屏幕后,就会产生相应的事件,所有相关的UITouch对象都被包装在事件中,被程序交由特定的对象来处理。UITouch对象直接包括触摸的详细信息。
UITouch类中包含5个属性:
  window:触摸产生时所处的窗口。由于窗口可能发生变化,当前所在的窗口不一定是最开始的窗口。
view:触摸产生时所处的视图。由于视图可能发生变化,当前视图也不一定时最初的视图。
tapCount:轻击(Tap)操作和鼠标的单击操作类似,tapCount表示短时间内轻击屏幕的次数。因此可以根据tapCount判断单击、双击或更多的轻击。
times*****p:时间戳记录了触摸事件产生或变化时的时间。单位是秒。
phase:触摸事件在屏幕上有一个周期,即触摸开始、触摸点移动、触摸结束,还有中途取消。而通过phase可以查看当前触摸事件在一个周期中所处的状态。phase是UITouchPhase类型的,这是一个枚举配型,包含了          · UITouchPhaseBegan(触摸开始)
· UITouchPhaseMoved(接触点移动)
· UITouchPhaseStationary(接触点无移动)
· UITouchPhaseEnded(触摸结束)
· UITouchPhaseCancelled(触摸取消)
UITouch类中包含如下成员函数:
- (CGPoint)locationInView:(UIView *)view:函数返回一个CGPoint类型的值,表示触摸在view这个视图上的位置,这里返回的位置是针对view的坐标系的。调用时传入的view参数为空的话,返回的时触摸点在整个窗口的位置。
- (CGPoint)previousLocationInView:(UIView *)view:该方法记录了前一个坐标值,函数返回也是一个CGPoint类型的值, 表示触摸在view这个视图上的位置,这里返回的位置是针对view的坐标系的。调用时传入的view参数为空的话,返回的时触摸点在整个窗口的位置。
当手指接触到屏幕,不管是单点触摸还是多点触摸,事件都会开始,直到用户所有的手指都离开屏幕。期间所有的UITouch对象都被包含在UIEvent事件对象中,由程序分发给处理者。事件记录了这个周期中所有触摸对象状态的变化。
只要屏幕被触摸,系统就会报若干个触摸的信息封装到UIEvent对象中发送给程序,由管理程序UIApplication对象将事件分发。一般来说,事件将被发给主窗口,然后传给第一响应者对象(FirstResponder)处理。
关于响应者的概念,通过以下几点说明:
   响应者对象(Response object)  响应者对象就是可以响应事件并对事件作出处理。在iOS中,存在UIResponder类,它定义了响应者对象的所有方法。UIApplication、UIView等类都继承了UIResponder类,UIWindow和UIKit中的控件因为继承了UIView,所以也间接继承了UIResponder类,这些类的实例都可以当作响应者。
          第一响应者(First responder)
  当前接受触摸的响应者对象被称为第一响应者,即表示当前该对象正在与用户交互,它是响应者链的开端。
   响应者链(Responder chain)  响应者链表示一系列的响应者对象。事件被交由第一响应者对象处理,如果第一响应者不处理,事件被沿着响应者链向上传递,交给下一个响应者(next responder)。一般来说,第一响应者是个视图对象或者其子类对象,当其被触摸后事件被交由它处理,如果它不处理,事件就会被传递给它的视图控制器对象(如果存在),然后是它的父视图(superview)对象(如果存在),以此类推,直到顶层视图。接下来会沿着顶层视图(top view)到窗口(UIWindow对象)再到程序(UIApplication对象)。如果整个过程都没有响应这个事件,该事件就被丢弃。一般情况下,在响应者链中只要由对象处理事件,事件就停止传递。但有时候可以在视图的响应方法中根据一些条件判断来决定是否需要继续传递事件。
   管理事件分发  视图对触摸事件是否需要作处回应可以通过设置视图的userInteractionEnabled属性。默认状态为YES,如果设置为NO,可以阻止视图接收和分发触摸事件。除此之外,当视图被隐藏(setHidden:YES)或者透明(alpha值为0)也不会收事件。不过这个属性只对视图有效,如果想要整个程序都步响应事件,可以调用UIApplication的beginIngnoringInteractionEvents方法来完全停止事件接收和分发。通过endIngnoringInteractionEvents方法来恢复让程序接收和分发事件。
如果要让视图接收多点触摸,需要设置它的multipleTouchEnabled属性为YES,默认状态下这个属性值为NO,即视图默认不接收多点触摸。
关于UIView的userInteractionEnabled属性
如果父视图为ParentView包含一个Button,如果再ParentView上添加子视图ChildView,且ChildView盖住了Button,那么Button就得到不响应了,
为了让Button响应,可以设置ChildView的userInteractionEnabled = NO;最近被这个问题困扰了很久,开始想用事件传递的方法,
重写类继承自UIView,最后被这简单属性搞定了....
键盘透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

状态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。

截取屏幕图片
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400)); 

//renderInContext 呈现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

 //返回一个基于当前图形上下文的图片
 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();

 //移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();

//以png格式返回指定图片的数据
imageData = UIImagePNGRepresentation(aImage);

更改cell选中的背景
    UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
    cell.selectedBackgroundView = myview; 
iPhone键盘改变颜色
只有这2种数字键盘才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad
keyboardAppearance = UIKeyboardAppearanceAlert 
代码如下:
  1.    NSArray *ws = [[UIApplication sharedApplication] windows];
  2.     for(UIView *w in ws){
  3.         NSArray *vs = [w subviews];
  4.         for(UIView *v in vs){
  5.             if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"]){
  6.                 v.backgroundColor = [UIColor redColor];
  7.             }
  8.         }
  9.     }
从一个界面push到下一界面左上角返回按钮文字设置
在父viewController中如下设置:
    UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];
    backbutton.title = @"返回列表";
    self.navigationItem.backBarButtonItem = backbutton;
    [backbutton release];

navigationbar的back键触发其他事件
UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)]; 
[back addTarget:self act
ion:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];
[back setImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];
self.navigationItem.leftBarButtonItem = loginButtonItem
[back release];
[backButtonItem release];
防止屏幕暗掉锁屏

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

将图片从左到右翻页效果显示
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];
    [imageView setImage:[UIImage imageNamed:@"Bg.jpg"]];
    self.myImageView =imageView;
    [self.view addSubview:imageView];
    [imageView release];
    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:nil context:context];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];
    [myImageView setFrame:CGRectMake(0, 0, 310, 470)];    
    [UIView commitAnimations];

让覆盖在下面层的视图接受触摸事件

searchImage.exclusiveTouch = YES;//第一层
searchImage.userInteractionEnabled = NO;
myMapView.exclusiveTouch = NO;//第二层
myMapView.userInteractionEnabled = YES;

View的缩放

NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain];
[UIView beginAnimations:nil context:touchPointValue];
transform = CGAffineTransformMakeScale(0.1,0.21);
firstPieceView.transform = transform;
[UIView commitAnimations];    
点击 UITextView 输入文字,光标都从最初点开始
能让用户点击 UITextView 输入文字时,光标都从最初点开始
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    NSRange range;
    range.location = 0;
    range.length  = 0;
    textView.selectedRange = range;
}
UITextView光标位置的设置
点击 UITextView 输入文字,光标都从最初点开始 


更改UITextView的光标的位置:

-(void)textViewDidChangeSelection:(UITextView*)textView
{
NSRange range;
range.location = 0;
range.length = 0;
textView.selectedRange =range;
}
以上是当在UITextView中输入文字的时候,光标都从最初点开始。


PS:UITextView有一个小BUG,如果其高度小于50的话,输入的时候其光标会往上偏移,从而看不到光标,如果大于50就不会出现这个问题。
UITextView在光标处添加文字
// 获得光标所在的位置
int location =contentTextView.selectedRange.location;
// 将UITextView中的内容进行调整(主要是在光标所在的位置进行字符串截取,再拼接你需要插入的文字即可)
NSString *content = contentTextView.text;
NSString *result = [NSStringstringWithFormat:@"%@[姓名变量]%@",[contentsubstringToIndex:location],[contentsubstringFromIndex:location]];
// 将调整后的字符串添加到UITextView上面
contentTextView.text = result;
如何设置UITextView的光标位置
UITextView * m_textInput;
//设置光标到输入文字的末尾
NSUInteger length = m_textInput.text.length;
m_textInput.selectedRange = NSMakeRange(length,0);                                    
UITextView方法 用法


UITextView限制行数的问题之前试了好多方法,最终解决了,解决方法非常简单,在UITextViewDelegate中加下面的方法即可:
-(BOOL)textView:(UITextView *)textViewshouldChangeTextInRange:(NSRange)range
 replacementText:(NSString*)text {
  
   if (textView.contentSize.height > 104){
      textView.text = [textView.text substringToIndex:[textView.textlength]-1];
       returnNO;
   }


   return YES;
}



-(void)textViewDidChangeSelection:(UITextView*)textView 
每次输入都知道

[textView becomeFirstResponder]

(void)textViewDidChange:(UITextView*)textView 当textView的内容发生改变时,会调用。。再此计算已经输入的字符个数。

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)rangereplacementText:(NSString *)text; {

if([@"\n" isEqualToString:text] == YES) {
  [textViewresignFirstResponder];
  returnNO;
  }
  returnYES;
}

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)rangereplacementText:(NSString *)text;
textview根据光标插入数据  

UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
//定位光标

    NSRange range = [opinion selectedRange];
NSMutableString *top = [[NSMutableString alloc] initWithString:[opinion text]];
NSString *addName = [NSString stringWithFormat:@"%@、",cell.textLabel.text];
    [top insertString:addName atIndex:range.location];
    opinion.text = top;
    [top release];
用NStimer每隔一定时间刷新界面
NSTimer *addEnemyTimer;
addEnemyTimer=[NSTimer scheduledTimerWithTimeInterval:(3.0) target:self selector:@selector(addEnemy) userInfo:nil repeats:YES];


可以尝试使用一个单独的线程来实现
多点触摸:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
当一个或多个手指触碰屏幕时,发送touchesBegan:withEvent:消息。 
当一个或多个手指在屏幕上移动时,发送touchesMoved:withEvent:消息。
当一个或多个手指离开屏幕时,发送touchesEnded:withEvent:消息。
iphone中的UITouch    
手指在屏幕上能达到的精度和鼠标指针有很大的不同。当用户触击屏幕时,接触
    区域实际上是椭圆形的,而且比用户想像的位置更靠下一点。根据触摸屏幕的手指、手指的尺寸、手指接触屏幕的力量、手指的方向、以及其它因素的不同,
其“接触部位”的尺寸和形状也有所不同。底层的多点触摸系统会分析所有的这些信息,为您计算出单一的触点。

    UIResponder 是所有响应者对象的基类,
    它不仅为事件处理,而且也为常见的响应者行为定义编程接口。UIApplication、UIView、和所有从UIView 派生出来的UIKit 类(包括UIWindow)都直接或间接地继承自UIResponder类。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    NSUInteger numTaps = [touch tapCount];
    if (numTaps < 2) {
    [self.nextResponder touchesBegan:touches withEvent:event];
    } else {
    [self handleDoubleTap:touch];
    }
    }

    缺省情况下,视图会接收触摸事件。但是,您可以将其userInteractionEnabled
    属性声明设置为NO,关闭事件传递的功能。

    在一定的时间内关闭事件的传递。应用程序可以调用UIApplication 的
    beginIgnoringInteractionEvents 方法,并在随后调用endIgnoringInteractionEvents 方法来实现这个目的。

    缺省情况下,视图只接收多点触摸序列的第一个触摸事件,而忽略
    所有其它事件。如果您希望视图处理多点触摸,就必须使它启用这个功能。在代码或Interface Builder 的查看器窗口中将视图的multipleTouchEnabled 属性设置为YES,就可以实现这个目标。
    将事件传递限制在某个单独的视图上。缺省情况下,视图的exclusiveTouch 属性被设置为NO。将这个属性设置为YES 会使相应的视图具有这样的特性:即当该视图正在跟踪触摸动作时,窗口中的其它视图无法同时进行跟踪,它们不能接收到那些触摸事件。
    多点触摸:
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
    - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

    当一个或多个手指触碰屏幕时,发送touchesBegan:withEvent:消息。
    当一个或多个手指在屏幕上移动时,发送touchesMoved:withEvent:消息。
    当一个或多个手指离开屏幕时,发送touchesEnded:withEvent:消息。
    当触摸序列被诸如电话呼入这样的系统事件所取消时,发送touchesCancelled:withEvent:消息。
    上面这些方法都和特定的触摸阶段(比如UITouchPhaseBegan)相关联,该信息存在于UITouch 对象的phase 属性声明中。
    为了处理给定阶段的事件,响应者对象常常从传入的集合参数中取得一或多个UITouch 对象,然后考察这些对象的属性或取得它们的位置(如果需要处理所有触摸对象,可以向该NSSet 对象发送anyObject 消息)。UITouch 类中有一个名为locationInView:的重要方法,如果传入self 参数值,它会给出触摸动作在响应者坐标系统中的位置(假定该响应者是一个UIView 对象,且传入的视图参数不为nil)。另外,还有一个与之平行的方法,可以给出触摸动作之前位置(previousLocationInView:)。UITouch 实例的属性还可以给出发生多少次触
    碰(tapCount)、触摸对象的创建或最后一次变化发生在什么时间(times*****p)、以及触摸处于什么阶段(phase)。

    - (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
    {
    UITouch *touch = [touches anyObject];
    if ([touch tapCount] == 2) {
    CGPoint tapPoint = [theTouch locationInView:self];
    // Process a double-tap gesture
    }
    }
    在touchesEnded:withEvent:方法中,当触击次数为一时,响应者对象就向自身发送一个performSelector:withObject:afterDelay:消息,其中的选择器标识由响应者对象实现的、用于处理单击手势的方法;第二个参数是一个NSValue 或NSDictionary 对象,用于保存相关的UITouch 对象;时延参数则表示单击和双击手势之间的合理时间间隔。
    在touchesBegan:withEvent:方法中,如果触击次数为二,响应者对象会向自身发送一个cancelPreviousPerformRequestsWithTarget:消息,取消当前被挂起和延期执行的调用。如果触碰次数不为二,则在指定的延时之后,先前步骤中由选择器标识的方法就会被调用,以处理单击手势。
Iphone开发-NSRunLoop概述和原理
1.什么是NSRunLoop?
我们会经常看到这样的代码:


- (IBAction)start:(id)sender
{
pageStillLoading = YES;
[NSThread detachNewThreadSelector:@selector(loadPageInBackground:)toTarget:self withObject:nil];
[progress setHidden:NO];
while (pageStillLoading) {
[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
[progress setHidden:YES];
}
  这段代码很神奇的,因为他会“暂停”代码运行,而且程序运行不会因为这里有一个while循环而受到影响。在[progress setHidden:NO]执行之后,整个函数像暂停了一样,停在循环里面,等loadPageInBackground里面的操作都完成了以后,
才让[progress setHidden:YES]运行。这样做就显得简单,而且逻辑很清晰。如果不这样做,就需要在loadPageInBackground里面表示load完成的地方调用[progress setHidden:YES],显得代码不紧凑而且容易出错。
那么具体什么是NSRunLoop呢?其实NSRunLoop的本质是一个消息机制的处理模式。如果你对vc++编程有一定了解,在windows中,有一系列很重要的函数SendMessage,PostMessage,GetMessage,
这些都是有关消息传递处理的API。但是在你进入到Cocoa的编程世界里面,我不知道你是不是走的太快太匆忙而忽视了这个很重要的问题,Cocoa里面就没有提及到任何关于消息处理的API,
开发者从来也没有自己去关心过消息的传递过程,好像一切都是那么自然,像大自然一样自然?在Cocoa里面你再也不用去自己定义WM_COMMAD_XXX这样的宏来标识某个消息,
也不用在switch-case里面去对特定的消息做特别的处理。难道是Cocoa里面就没有了消息机制?答案是否定的,只是Apple在设计消息处理的时候采用了一个更加高明的模式,那就是RunLoop。
利用NSRunLoop阻塞NSOperation线程
在使用NSOperationQueue简化多线程开发中介绍了多线程的开发,我这里主要介绍一下使用NSRunLoop阻塞线程。
主要使用在NStimer定时启用的任务或者异步获取数据的情况如socket获取网络数据,要阻塞线程,直到获取数据之后在释放线程。
下面是线程中没有使用NSRunLoop阻塞线程的代码和执行效果:
线程类:
#import <Foundation/Foundation.h> 
@interface MyTask : NSOperation {     

@end
#import "MyTask.h" 
@implementation MyTask 
-(void)main     
{      
    NSLog(@"开始线程=%@",self);      
    [NSTimer timerWithTimeInterval:2 target:self selector:@selector(hiandeTime:) userInfo:nil repeats:NO];      
}      
-(void)hiandeTime:(id)sender      
{      
    NSLog(@"执行了NSTimer");      
}      
-(void)dealloc      
{      
    NSLog(@"delloc mytask=%@",self);      
    [super dealloc];      

@end
线程添加到队列中:


- (void)viewDidLoad     
{      
    [super viewDidLoad];      
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];      
    MyTask *myTask=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask];      
    MyTask *myTask1=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask1];      
    MyTask *myTask2=[[[MyTask alloc] init] autorelease];      
    [queue addOperation:myTask2];      
    [queue release];      
}
执行结果是:
2011-07-25 09:44:45.393 OperationDemo[20676:1803] 开始线程=<MyTask: 0x4b4dea0>   
2011-07-25 09:44:45.393 OperationDemo[20676:5d03] 开始线程=<MyTask: 0x4b50db0>    
2011-07-25 09:44:45.396 OperationDemo[20676:1803] 开始线程=<MyTask: 0x4b51070>    
2011-07-25 09:44:45.404 OperationDemo[20676:6303] delloc mytask=<MyTask: 0x4b4dea0>    
2011-07-25 09:44:45.404 OperationDemo[20676:5d03] delloc mytask=<MyTask: 0x4b50db0>    
2011-07-25 09:44:45.405 OperationDemo[20676:6303] delloc mytask=<MyTask: 0x4b51070>
可以看到,根本没有执行NSTimer中的方法,线程就释放掉了,我们要执行
NSTimer中的方法,就要利用NSRunLoop阻塞线程。下面是修改后的代码:

-(void)main     
{      
    NSLog(@"开始线程=%@",self);      
    NSTimer *timer=[NSTimer timerWithTimeInterval:2 target:self selector:@selector(hiandeTime) userInfo:nil repeats:NO];      
    [timer fire];      
    while (!didDisconnect) {      
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];      
    }      
}
执行结果如下:
2011-07-25 10:07:00.543 OperationDemo[21270:1803] 开始线程=<MyTask: 0x4d16380>     
2011-07-25 10:07:00.543 OperationDemo[21270:5d03] 开始线程=<MyTask: 0x4d17790>      
2011-07-25 10:07:00.550 OperationDemo[21270:6303] 开始线程=<MyTask: 0x4d17a50>      
2011-07-25 10:07:00.550 OperationDemo[21270:1803] 执行了NSTimer      
2011-07-25 10:07:00.551 OperationDemo[21270:5d03] 执行了NSTimer      
2011-07-25 10:07:00.552 OperationDemo[21270:6303] 执行了NSTimer      
2011-07-25 10:07:00.556 OperationDemo[21270:6503] delloc mytask=<MyTask: 0x4d16380>      
2011-07-25 10:07:00.557 OperationDemo[21270:6303] delloc mytask=<MyTask: 0x4d17790>      
2011-07-25 10:07:00.557 OperationDemo[21270:5d03] delloc mytask=<MyTask: 0x4d17a50>
我们可以使用NSRunLoop进行线程阻塞。
ASIHTTPRequest 一款强大的HTTP包装开源项目   
ASIHTTPRequest,是一个直接在CFNetwork上做的开源项目,提供了一个比官方更方便更强大的HTTP网络传输的封装。
特色功能如下:
1,下载的数据直接保存到内存或文件系统里
2,提供直接提交(HTTP POST)文件的API
3,可以直接访问与修改HTTP请求与响应HEADER
4,轻松获取上传与下载的进度信息
5,异步请求与队列,自动管理上传与下载队列管理机
6,认证与授权的支持
7,Cookie
8,请求与响应的GZIP
9,代理请求


下面来两个小例子:
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request start];
NSError *error = [request error];
if (!error) {
    NSString *response = [request responseString];
}

当你需要添加更多的请求信息时,如,添加个请求Header:
[request addRequestHeader:@"name" value:@"Jory lee"];

添加Post请求时的健值:
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

设置HTTP的授权帐号:
[request setUsername:@"username"];
[request setPassword:@"password"];

一个异步请求:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];

// Use when fetching binary data
NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}   

在我们数据获取的过程中,如果数据源复杂,一个请求队列是必不可少的:
- (IBAction)grabURLInTheBackground:(id)sender
{
if (![self queue]) {
[self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
}

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
}

- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}

- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}   
ASIHTTPRequest使用介绍

SIHTTPRequest,是一个直接在CFNetwork上做的开源项目,提供了一个比官方更方便更强大的HTTP网络传输的封装。
一、介绍
特色功能如下:
1.下载的数据直接保存到内存或文件系统里
2.提供直接提交(HTTP POST)文件的API
3.可以直接访问与修改HTTP请求与响应HEADER
4.轻松获取上传与下载的进度信息
5.异步请求与队列,自动管理上传与下载队列管理机
6.认证与授权的支持
7.Cookie
8.请求与响应的GZIP
9.代理请求
ASIHTTPRequest -Main classes介绍:
1.ASIHTTPRequest:处理与服务器的基本交互,包括下载上传,认证,cookies以及进度查看。
2.ASIFormDataRequest:是ASIHTTPRequest子类,主要处理post事件,它能使post更加简单。
3.ASINetworkQueue:是NSOperationQueue子类,当处理多个请求时可以使用,如果每次都是单个请求就不必使用。
4.ASIDownloadCache:该类允许ASIHTTPRequest从服务器传递cookie。
ASIHTTPRequest -Support classes介绍:
1.ASIInputStream:当使用ASIHTTPRequest上传数据时使用,如果工程中用了ASIHTTPRequest,就一定要include这个类。
2.ASIAuthenticationDialog:该类允许ASIHTTPRequest连接到服务器时呈现登录框。在所有iPhone OS工程中都要使用,Mac OS工程中可以不用。
3.Reachability:相信很多人对这个类已经很熟悉了,当在你程序中侦测网络状态时它将非常有用。
ASIHTTPRequest -Protocols and configuration介绍:
1.ASIHTTPRequestDelegate:该协议指定了ASIHTTPRequest的delegate可能需要实现的方法,所有方法都是optional。
2.ASIProgressDelegate:该协议列出了uploadProgressDelegate和downloadProgressDelegate可能需要实现的方法,所有方法为optional。
3.ASICacheDelegate:该协议指定了download cache必须实现的方法。如果你要写你自己的download cache,确保实现required方法。
4.ASIHTTPRequestConfig.h:该文件定义了编译时所有的全局配置选项。使用该文件中的方法可以在控制台中输出request正在进行的任务.
 
原址:http://www.cocoachina.com/bbs/read.php?tid=73570
 

Iphone 开发常用代码   

 
 
更改cell选中的背景
    UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
    cell.selectedBackgroundView = myview;

在数字键盘上添加button:
//定义一个消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注册一个观察员 name:消息名称
- (void)keyboardWillShow:(NSNotification *)note {
    // create custom button
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    [doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
   
    // locate keyboard view
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回应用程序window
    UIView* keyboard;
    for(int i=0; i<[tempWindow.subviews count]; i++) //遍历window上的所有subview
    {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        // keyboard view found; add the custom button to it
        if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
        [keyboard addSubview:doneButton];
    }
}

正则表达式使用
被用于正则表达式的字串必须是可变长的,不然会出问题

将一个空间放在视图之上
[scrollView insertSubview:searchButton aboveSubview:scrollView];

从本地加载图片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src='0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];

从网页加载图片并让图片在规定长宽中缩小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];
将网页加载到webview上通过javascript获取里面的数据,如果只是发送了一个连接请求获取到源码以后可以用正则表达式进行获取数据
NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";
NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];

用NSString怎么把UTF8转换成unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];

View自己调用自己的方法:
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黄色段为方法名,和延迟几秒执行.

显示图像:
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];

WebView:
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];

显示网络活动状态指示符
这是在iPhone左上部的状态栏显示的转动的图标指示有背景发生网络的活动。
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;

动画:一个接一个地显示一系列的图象
NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages; //animationImages属性返回一个存放动画图片的数组
myAnimatedView.animationDuration = 0.25; //浏览整个图片一次所用的时间
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 动画重复次数
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];

动画:显示了something在屏幕上移动。注:这种类型的动画是“开始后不处理” -你不能获取任何有关物体在动画中的信息(如当前的位置) 。如果您需要此信息,您会手动使用定时器去调整动画的X和Y坐标
这个需要导入QuartzCore.framework
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];

Draggable items//拖动项目
Here's how to create a simple draggable image.//这是如何生成一个简单的拖动图象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point 检索接触点
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Move relative to the original touch point 相对以前的触摸点进行移动
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
3. Now instantiate the new class as you would any other new image and add it to your view
//实例这个新的类,放到你需要新的图片放到你的视图上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];

线程:
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
{
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
}
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];

Alerts
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];

Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews])
{
if (anImage.tag == 1)
        { // do something }
}

转自:http://www.cnblogs.com/rosylxf/archive/2012/07/12/2588672.html
 
原创粉丝点击