在iphone程序中实现截屏的一种方法:

//导入头文件   #importQuartzCore/QuartzCore.h

//将整个self.view大小的图层形式创建一张图片imageUIGraphicsBeginImageContext(self.view.bounds.size);

[self.view.layerrenderInContext: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的使用

延时函数:

[NSThreadsleepForTimeInterval:5.0]; //暂停5s.

Timer的使用:

NSTimer*connectionTimer;  //timer对象

//实例化timer

self.connectionTimer=[NSTimerscheduledTimerWithTimeInterval:1.5target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];

[[NSRunLoopcurrentRunLoop] addTimer: self.connectionTimer forMode: NSDefaultRunLoopMode];  //用timer作为延时的一种方法

do{

[[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];

} while(!done);

//timer调用函数

-(void)timerFired:(NSTimer*)timer {

done =YES;   }

使用NSTimer与iphone的简单动画,实现飘雪效果

使用NSTimer与iphone的简单动画,实现飘雪效果,这理原理比较简单,就是定时生成一定的雪花图片,然后使用动画的方式向下漂落(我在其它论坛,看到使用path的方式实现的一个云漂来漂去的效果,实际也可以用那种方式实现,这实际就是前面说的动画效果的两种应用)。所以,我们可以在 viewDidLoad事件中,增加一个图片及定时器并启动,这里的pic请在头文件中定义。

-(void)viewDidLoad{

[super viewDidLoad];

self.pic =[UIImage imageNamed:@"snow.png"];//初始化图片

//启动定时器,实现飘雪效果

[NSTimerscheduledTimerWithTimeInterval:(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.viewaddSubview:view];//添加该view

[UIViewbeginAnimations:nil context:view];//开始动画

[UIViewsetAnimationDuration:10*sp];//设定速度

view.frame =CGRectMake(y, 500, s, s);//设定该雪花最后的消失坐标

[UIViewsetAnimationDelegate:self];

[UIViewcommitAnimations];

}

使用NSTimer实现倒计时

今天在CocoaChina上面看到有人在问倒计时怎么做,记得以前在看Iphone31天的时候做过一个,今天翻出来运行不了了,原因是我的IphoneSDK升级到3.1了,以前使用的是2.2.1,在2.2.1里面是可以使用NSCalendarDate的,但是在3.1里面不能够使用,怎么办,只好用NSTimer了,最后还是给实现了。代码也比较简单,开始运行viewDidLoad的时候加载

[NSTimerscheduledTimerWithTimeInterval:1.0target:selfselector:@selector(timerFireMethod:) userInfo:nilrepeats:YES];//使用timer定时,每秒触发一次

,然后就是写selector了。

-(void)timerFireMethod:(NSTimer*)theTimer{

//NSDateFormatter*dateformatter =[[[NSDateFormatter alloc]init]autorelease];//定义NSDateFormatter用来显示格式

//[dateformattersetDateFormat:@"yyyy MM dd hh mmss"];//设定格式

NSCalendar*cal = [NSCalendarcurrentCalendar];//定义一个NSCalendar对象

NSDateComponents*shibo = [[NSDateComponentsalloc] init];//初始化目标时间(好像是世博会的日期)

[shibosetYear:2010];

[shibosetMonth:5];

[shibosetDay:1];

[shibosetHour:8];

[shibosetMinute:0];

[shibosetSecond:0];

NSDate *todate= [caldateFromComponents:shibo];//把目标时间装载入date

[shiborelease];

// NSString*ssss = [dateformatterstringFromDate:dd];

// NSLog([NSStringstringWithFormat:@"shiboshi:%@",ssss]);

NSDate *today= [NSDate date];//得到当前时间

// NSString*sss = [dateformatterstringFromDate:today];

// NSLog([NSStringstringWithFormat:@"xianzaishi:%@",sss]);

//用来得到具体的时差

unsigned intunitFlags = 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秒",[dyear],[d month], [d day],[d hour], [d minute], [d second]];

}  这样就实现了倒计时的功能。

NSTimer的用法

iPhone为我们提供了一个很强大得时间定时器 NSTimer,它可以完成任何定时功能:

我们使用起来也很简单,只要记住三要素就可以,具体得三要素是:时间间隔NSTimeInterval浮点型,事件代理delegate和事件处理方法@selector();

就可以用

1 +(NSTimer*)scheduledTimerWithTimeIn

2terval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelectoruserInfo:(id)userInfo repeats:(BOOL)yesOrNo;

[/pre]来初始化一个 时间定时器

下面我写了一个很简单得例子:

-(void)initTimer {

//时间间隔4 NSTimeInterval timeInterval =1.0;

//定时器6 NSTimer   showTimer =[NSTimerscheduledTimerWithTimeInterval:maxShowTime

target:self

selector:@selector(handleMaxShowTimer:)

userInfo:nil

repeats:NO];

}

//触发事件

-(void)handleMaxShowTimer:(NSTimer*)theTimer {

NSDateFormatterdateFormator =[[NSDateFormatter alloc] init];

dateFormator.dateFormat=@"yyyy-MM-dd  HH:mm:ss";

NSString *date=[dateformater stringFromDate:[NSDate date]];

if([dateisEqualToString:@"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];

[dateFormatorrelease];

}

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:[NSStringstringWithFormat:@"%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();   }用这种方法播放好像挺占用资源的,比较卡,以后再研究研究其它的方法。

截取屏幕图片

//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)

UIGraphicsBeginImageContext(CGSizeMake(200,400));

//renderInContext 呈现接受者及其子范围到指定的上下文

[self.view.layerrenderInContext:UIGraphicsGetCurrentContext()];

//返回一个基于当前图形上下文的图片

UIImage*aImage =UIGraphicsGetImageFromCurrentImageContext();

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

UIGraphicsEndImageContext();

//以png格式返回指定图片的数据

imageData = UIImagePNGRepresentation(aImage);

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.viewremoveFromSuperview];

[timer invalidate];//这句代码用来终止timmer,否则,每过1.5秒,就会执行该方法一次,我们是要在开始的时候执行一次就够了。

}

让一个UIImageView响应点击事件

UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0,320, 44)];

imgView.userInteractionEnabled=YES;

UITapGestureRecognizer*singleTap =[[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(onClickImage)];

[imgViewaddGestureRecognizer:singleTap];

[singleTap release];

-(void)onClickImage{   // here, do whatever you wantto do

NSLog(@"imageviewis clicked!");

}

启动界面的制作

iPhone开发实现splash画面非常简单,做一个全屏的欢迎页的图片,把它命名为Default.png,然后放在Xcode工程的Resource里面。在XXXAppDelegate.m程序中,插入如下代码:

- (BOOL)application:(UIApplication*)application

didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[NSThread sleepForTimeInterval:5.0];

[windowaddSubview:viewController.view];

[windowmakeKeyAndVisible];

return YES;

}  这样splash页面就停留5秒后,消失了。

关于控制器Controller的思考

iPhone开发中,只有一个窗口,对应的是多个视图,而视图的组织形式各种各样,关键是要靠控制器来组织各个视图的逻辑关系。大体的关系如下:

窗体---主控制器(比如说导航控制器),主控制器在窗体里面,拖动过去即可,在AppDelegate中写相关变量的代码---在主控制器下有别的控制器,比如视图控制器,可以通过interfacebuilder来关联根视图什么的----视图控制器相当于一个根视图,可以调用其他的视图---视图中包含类文件(.h,.m)和图形界面文件(.xib)(两个之间必须关联起来。)

翻页效果

经常看到iPhone的软件向上向下翻页面的效果,其实这个很简单,已经有封装好的相关方法处理。

//首先设置动画的相关参数

[UIViewbeginAnimations:@"Curl"context:nil];

[UIViewsetAnimationDuration:1.25]; //时间

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];//速度

//然后设置动画的动作和目标视图

[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];

参数UIViewAnimationTransitionCurlUp代表向上翻页,如果向下的话UIViewAnimationTransitionCurlDown.

forView那把当前的视图传进去。

//最后提交动画

[UIView commitAnimations];

自定义按钮

UIButton *Btn;

CGRectframe;

Btn = [[UIButtonbuttonWithType:UIButtonTypeCustom] retain]; //按钮的类型    [BtnsetImage:[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;

[BtnsetFrame:frame];

[BtnsetBackgroundColor:[UIColor clearColor]];

 [Btn addTarget:selfaction:@selector(btnPressed:)forControlEvents:UIControlEventTouchUpInside];  //按钮的单击事件    

[self.view addSubview:Btn];

[Btn release];

-(void)btnPressed:(id)sender{

//在这里实现按钮的单击事件   }

读取和写入plist文件

plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法: 以下代码在Mac和iPhone中均适用。

写入plist文件: NSMutableDictionary * dict = [ [ NSMutableDictionaryalloc ] initWith

plist文件是标准的xml文件,在cocoa中可以很简单地使用。这里介绍一下使用方法:

以下代码在Mac和iPhone中均适用。

写入plist文件:

NSMutableDictionary* dict= [ [ NSMutableDictionaryalloc ]initWithContentsOfFile:@"/Sample.plist"];

[ dictsetObject:@"Yes"forKey:@"RestartSpringBoard"];

[ dictwriteToFile:@"/Sample.plist"atomically:YES];

读取plist文件:

NSMutableDictionary* dict=  [ [ NSMutableDictionaryalloc ]initWithContentsOfFile:@"/Sample.plist"];

NSString* object = [ dictobjectForKey:@"RestartSpringBoard" ];

iphone 学习笔记

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

/*********************************************************

1、取随机数:

NSData *datanow = [NSDatadata];

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 = [[NSURLalloc] initFileURLWithPath:musicFilePath];

musicPlayer=[[AVAudioPlayeralloc] initWithContentsOfURL:musicURL error:nil];

[musicURL release];

//[musicPlayerprepareToPlay];

//[musicPlayersetVolume: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 =[homeDirectorystringByAppendingPathComponent:@"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:[NSStringstringWithUTF8String:"///mest.txt"]];

NSLog(@"filepath:%@",filepath);

BOOLsuccess =[[NSFileManagerdefaultManager]createFileAtPath: filepathcontents:nilattributes:nil];

NSLog(@"result",success);

printf("CreateFile:%s %s.",[filepath UTF8String], success ? "Success":"Error");

NSString* reValue= [NSStringstringWithString:@"\"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];

[formattersetDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSString*locationString=[formatter stringFromDate: [NSDate date]];

//获取当前时间作为productId

NSDateFormatter*formatter= [[NSDateFormatteralloc] init];

[formattersetDateFormat:@"hhmmss"];

NSString *locationString=[formatterstringFromDate: [NSDate date]];

downloadInfo.productId =locationString;

[formatter release];

/**********************************************************

函数名称  : getDate

函数描述  : 获取当前日期时间

输入参数  : N/A

输出参数  : N/A

返回值    : NSString 当前时间

备注     :***********

{

NSDateFormatter*formatter = [[NSDateFormatteralloc]init];

[formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ssa"];

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 StandardTime; PST; GMT-08:00

Z  时区  RFC 822 time zone  -0800

/**********************************************************

关于UIView的userInteractionEnabled属性

如果父视图为ParentView包含一个Button,如果再ParentView上添加子视图ChildView,且ChildView盖住了Button,

那么Button就得到不响应了,为了让Button响应,可以设置ChildView的userInteractionEnabled = NO;

最近被这个问题困扰了很久,开始想用事件传递的方法,重写类继承自UIView,最后被这简单属性搞定了....

createtoolbar using new

  toolbar= [UIToolbar new];

  toolbar.barStyle= UIBarStyleDefault;

  [toolbarsizeToFit];

  toolbar.frame = CGRectMake(0, 410, 320, 50);

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.viewaddSubview:parentView];

}//需要在h头文件声明下面的动作响应函数

//在xib文件中添加一个button,其响应函数为下面的函数

//运行程序后,点击button就看到翻转效果

-(IBAction)ActionFanzhuan{

//获取当前画图的设备上下文

CGContextRef context= UIGraphicsGetCurrentContext();

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

//设置动画曲线,翻译不准,见苹果官方文档 

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];

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

//因为没给viewController类添加成员变量,所以用下面方法得到viewDidLoad添加的子视图

UIView *parentView =[self.view viewWithTag:1000]; //设置动画效果

[UIViewsetAnimationTransition: UIViewAnimationTransitionCurlDown forView:parentViewcache:YES];  //从上向下

// [UIViewsetAnimationTransition: UIViewAnimationTransitionCurlUp forView:parentViewcache:YES];   //从下向上

// [UIViewsetAnimationTransition: UIViewAnimationTransitionFlipFromLeftforView:parentView cache:YES];  //从左向右// [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:parentView cache:YES];//从右向左 //设置动画委托

[UIViewsetAnimationDelegate:self];

//当动画执行结束,执行animationFinished方法

[UIViewsetAnimationDidStopSelector:@selector(animationFinished:)];

//提交动画 [UIView commitAnimations];  }//动画效果执行完毕

- (void)animationFinished: (id) sender{NSLog(@"animationFinished !");

} 运行程序,点击按钮,就能看到动画效果了。

 iPhone实现动画效果

iPhone中实现动画,主要有两种方式:UIView的动画块和CoreAnimation的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倍):

[UIViewsetAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:self.viewcache:YES];

其中,参数UIViewAnimationTransitionFlipFromLeft定义了翻转的方式。

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";

//@"1InfiniteLoop, 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

[[UIApplicationsharedApplication]openURL:[NSURL   URLWithString:@"mailto://devprograms@apple.com"]];    }

-(IBAction)openPhone {  //拨打电话  // CallGoogle 411

[[UIApplication sharedApplication]openURL:[NSURLURLWithString:@"tel://8004664411"]];    }

- (IBAction)openSms{  //打开短信  // Text toGoogleSMS

[[UIApplicationsharedApplication] 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=[[CLLocationManageralloc]init];

[locmanagersetDelegate:self];

//设置精确度

[locmanagersetDesiredAccuracy:kCLLocationAccuracyBest];

[locmanagerstartUpdatingLocation];

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

在代理方法:

-(void)locationManager:(CLLocationManager*)managerdidUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation{

//初始化矩形大小

CGRectrect=CGRectMake(0,0,320,460);

//设置地图大小为矩形大小

map=[[MKMapViewalloc] initWithFrame:rect];

CLLocationCoordinate2Dloc=[newLocation coordinate];

lat=loc.latitude;

lon=loc.longitude;

//coordinate坐标

CLLocationCoordinate2DtheCoordinate;

CLLocationCoordinate2DtheCenter;

//theCoordinate.latitude=lat;

//theCoordinate.longitude=lon;

theCoordinate=loc;

[mapsetDelegate:self];

//设置地图显示的类型,有卫星地图,道路,等

[mapsetMapType: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;

returnnewAnnotation;

}

键盘透明

textField.keyboardAppearance= UIKeyboardAppearanceAlert;

状态栏的网络活动风火轮是否旋转

[UIApplicationsharedApplication].networkActivityIndicatorVisible,默认值是NO。

关于UIView的userInteractionEnabled属性

如果父视图为ParentView包含一个Button,如果再ParentView上添加子视图ChildView,且ChildView盖住了Button,那么Button就得到不响应了,

为了让Button响应,可以设置ChildView的userInteractionEnabled= NO;最近被这个问题困扰了很久,开始想用事件传递的方法,

重写类继承自UIView,最后被这简单属性搞定了....

UIPageControl实现自定义按钮

 

有时候UIPageControl需要用到白色的背景, 那么会导致上面的点按钮看不见或不清楚,

我们可以通过继承该类重写函数来更换点按钮的图片现实.

实现思路如下.

新建类继承UIPageControl :

@interfaceMyPageControl : 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

@implementationMyPageControl  //实现部分

@synthesizeimagePageStateNormal;

@synthesizeimagePageStateHighlighted;

-(id)initWithFrame:(CGRect)frame { // 初始化

    self= [superinitWithFrame:frame];

    returnself;    }

-(void)setImagePageStateNormal:(UIImage*)image {  // 设置正常状态点按钮的图片

    [imagePageStateNormalrelease];

    imagePageStateNormal=[image retain];

    [selfupdateDots];    }

-(void)setImagePageStateHighlighted:(UIImage*)image { // 设置高亮状态点按钮图片

    [imagePageStateHighlightedrelease];

    imagePageStateHighlighted=[image retain];

[self updateDots];   

}

-(void)endTrackingWithTouch:(UITouch*)touch withEvent:(UIEvent *)event { // 点击事件

    [superendTrackingWithTouch:touchwithEvent:event];

[self updateDots];   

}

-(void)updateDots { // 更新显示所有的点按钮

    if(imagePageStateNormal|| imagePageStateHighlighted) {

        NSArray*subview= self.subviews;  // 获取所有子视图

        for(NSIntegeri = 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;

    [superdealloc];

}

@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"]];

[pageControlsetImagePageStateHighlighted:[UIImageimageNamed:@"pageControlStateHighlighted.png"]];

[self.viewaddSubview:pageControl];

[pageControl release];

iPhone电子书toolbar的实现

iPhone电子书的toolbar一般都设计成半透明,上面放置一个进度条和一个Label(用于显示页码),这里用代码做一个最基本的实现。//生成一个UIToolbar

UIToolbar *toolbar=[[[UIToolbar alloc] init] autorelease];

toolbar.barStyle=UIBarStyleBlackTranslucent;

[toolbar sizeToFit];

CGFloattoolbarHeight =[toolbar frame].size.height;

CGRectrootViewBounds =self.parentViewController.view.bounds;

CGFloat rootViewHeight=CGRectGetHeight(rootViewBounds);

CGFloatrootViewWidth =CGRectGetWidth(rootViewBounds);

CGRect rectArea =CGRectMake(0, rootViewHeight-toolbarHeight,rootViewWidth, toolbarHeight);

[toolbarsetFrame: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:[[[UIBarButtonItemalloc]initWithCustomView:readSlider] autorelease]];

[tbitems addObject:[[[UIBarButtonItemalloc] initWithCustomView:readLabel]autorelease]];

toolbar.items =tbitems;

toolbar加入到当前view中

[self.navigationController.viewaddSubview: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

是在局部坐标系统

很明显,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的坐标系的坐标和大小.

区别主要在坐标系这一块。

很明显一个是自己为原点的坐标系,一个是以屏幕为原点的坐标系。

多使用宏定义常量。tag,frame大小,一些判断标志位。

#define kIndexValueTag 1

苹果屏幕截图快捷键

一般在Mac上用Command-Shif-3/4来截图。注:Command=苹果键 其实还有几个辅助键,来起到不同的截图功能……

1)Command-Shift-3(适用于OS9,10.1X和10.2)

将整个屏幕拍下并保存到桌面。

2)Command-Shift-4(适用于OS9,10.1X和10.2)

将屏幕的一部分拍下并保存到桌面。当按下着几个键后,光标会变为一个十字,可以拖拉来选取拍报区域。

3)Command-Shift-Control-3(适用于OS9和10.2)

将整个屏幕拍下并保存到剪贴板,可以Command+V直接粘贴到如Photoshop等软件中编辑。

4)Command-Shift-Control-4(适用于OS9和10.2)

将屏幕的一部分拍下并保存到剪贴板。

5)Command-Shift-4再按空格键(适用于10.2)

光标会变成一个照相机,点击可拍下当前窗口或菜单或Dock以及图标等,只要将照相机移动到不用区域(有效区域会显示为浅蓝色)点击。

6)Command-Shift-Control-4再按空格键(适用于10.2)

将选取的窗口或其他区域的快照保存到剪贴板。

7)Command-Shift-Capslock-4(适用于OS9)

将当前的窗口拍下并保存到桌面。

8)Command-Shift-Capslock-Control-4(适用于OS9)

将当前的窗口拍下并保存到剪贴板。

设置透明度  [myViewsetAlpha:value];   (0.0 < value <1.0)

设置背景色

[myViewsetBackgroundColor:[UIColor redColor]];

(blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor;redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;

3     orangeColor;purpleColor;brownColor;clearColor; )

自定义颜色:

UIColor*newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float)alpha:(float)];      0.0~1.0

宽度和高度

768X1024     1024X768   状态栏高20 像素高   导航栏 工具栏 44像素高

隐藏状态栏:[[UIApplicationshareApplication]setStatusBarHidden:YES animated:NO]

iphone界面如何实现下拉列表

代码如下:

#import<UIKit/UIKit.h>

@interfaceDropDownList : UIView<UITableViewDelegate,UITableViewDataSource> {

UITextField*textField;   //文本输入框

NSArray*list;            //下拉列表数据

BOOLshowList;             //是否弹出下拉列表

UITableView*listView;    //下拉列表

CGRectoldFrame,newFrame;   //整个控件(包括下拉前和下拉后)的矩形

UIColor*lineColor,*listBgColor;//下拉框的边框色、背景色

CGFloatlineWidth;               //下拉框边框粗细

UITextBorderStyleborderStyle;   //文本框边框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"

@implementationDropDownList

@synthesizetextField,list,listView,lineColor,listBgColor,borderStyle;

-(id)initWithFrame:(CGRect)frame {

if(self=[superinitWithFrame:frame]){

//默认的下拉列表中的数据

list=[[NSArrayalloc]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=[UIColorlightGrayColor];//默认列表边框线为灰色

listBgColor=[UIColorwhiteColor];//默认列表框背景色为白色

lineWidth=1;    //默认列表边框粗细为1

//把背景色设置为透明色,否则会有一个黑色的边

self.backgroundColor=[UIColorclearColor];

[selfdrawView];//调用方法,绘制控件

}

returnself;

}

-(void)drawView{

//文本框

textField=[[UITextFieldalloc]

initWithFrame:CGRectMake(0, 0,

oldFrame.size.width,

oldFrame.size.height)];

textField.borderStyle=borderStyle;//设置文本框的边框风格

[selfaddSubview:textField];

[textField addTarget:self action:@selector(dropdown)forControlEvents:UIControlEventAllTouchEvents];

//下拉列表

listView=[[UITableViewalloc]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的值显示或隐藏

[selfaddSubview:listView];

[listViewrelease];   }

-(void)dropdown{

[textFieldresignFirstResponder];

if(showList){//如果下拉框已显示,什么都不做

return;

}else{//如果下拉框尚未显示,则进行显示

//把dropdownList放到前面,防止下拉框被别的控件遮住

[self.superviewbringSubviewToFront:self];

[selfsetShowList:YES];//显示下拉框    }   }

#pragmamark listViewdataSource method and delegate method

-(NSInteger)tableView:(UITableView*)table numberOfRowsInSection:(NSInteger)section{

returnlist.count;

}

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

staticNSString *cellid=@"listviewid";

UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:cellid];

if(cell==nil){

cell=[[[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefault

reuseIdentifier:cellid]autorelease];

} //文本标签

cell.textLabel.text=(NSString*)[listobjectAtIndex:indexPath.row];

cell.textLabel.font=textField.font;

cell.selectionStyle=UITableViewCellSelectionStyleGray;

returncell;

}

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

returnoldFrame.size.height;

}

//当选择下拉列表中的一行时,设置文本框中的值,隐藏下拉列表

-(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//NSLog(@"select");

textField.text=(NSString*)[listobjectAtIndex:indexPath.row];

//NSLog(@"textField.text=%@",textField.text);

[selfsetShowList:NO];

}

-(BOOL)showList{//setShowList:No为隐藏,setShowList:Yes为显示

returnshowList;

}

-(void)setShowList:(BOOL)b{

showList=b;

NSLog(@"showlistis 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

iphone之UISegmentedControl

代码://选择按钮

NSArray*buttonNames = [NSArray arrayWithObjects:@"今天", @"本周", @"本月",nil];

UISegmentedControl* segmentedControl = [[UISegmentedControlalloc]initWithItems:buttonNames];

[segmentedControl setFrame:CGRectMake(60, 10, 200, 40)];

segmentedControl.selectedSegmentIndex=1;

//添加事件

[segmentedControladdTarget:selfaction:@selector(segmentAction:)forControlEvents:UIControlEventValueChanged];

[self.viewaddSubview:segmentedControl];

[segmentedControl release];

//事件

-(void)segmentAction:(UISegmentedControl*)Seg{

NSIntegerIndex = Seg.selectedSegmentIndex;

NSLog(@"Seg.selectedSegmentIndex:%d",Index);    }

iOS Programming – 触摸事件处理

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

在Cocoa中,代表触摸对象的类是UITouch。当用户触摸屏幕后,就会产生相应的事件,所有相关的UITouch对象都被包装在事件中,被程序交由特定的对象来处理。UITouch对象直接包括触摸的详细信息。

 

UITouch类中包含5个属性:

window:触摸产生时所处的窗口。由于窗口可能发生变化,当前所在的窗口不一定是最开始的窗口。

view:触摸产生时所处的视图。由于视图可能发生变化,当前视图也不一定时最初的视图。

tapCount:轻击(Tap)操作和鼠标的单击操作类似,tapCount表示短时间内轻击屏幕的次数。因此可以根据tapCount判断单击、双击或更多的轻击。

timestamp:时间戳记录了触摸事件产生或变化时的时间。单位是秒。

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类,这些类的实例都可以当作响应者。

第一响应者(Firstresponder)

当前接受触摸的响应者对象被称为第一响应者,即表示当前该对象正在与用户交互,它是响应者链的开端。

    响应者链(Responder chain)  响应者链表示一系列的响应者对象。事件被交由第一响应者对象处理,如果第一响应者不处理,事件被沿着响应者链向上传递,交给下一个响应者(next responder)。一般来说,第一响应者是个视图对象或者其子类对象,当其被触摸后事件被交由它处理,如果它不处理,事件就会被传递给它的视图控制器对象(如果存在),然后是它的父视图(superview)对象(如果存在),以此类推,直到顶层视图。接下来会沿着顶层视图(top view)到窗口(UIWindow对象)再到程序(UIApplication对象)。如果整个过程都没有响应这个事件,该事件就被丢弃。一般情况下,在响应者链中只要由对象处理事件,事件就停止传递。但有时候可以在视图的响应方法中根据一些条件判断来决定是否需要继续传递事件。

管理事件分发  视图对触摸事件是否需要作处回应可以通过设置视图的userInteractionEnabled属性。默认状态为YES,如果设置为NO,可以阻止视图接收和分发触摸事件。除此之外,当视图被隐藏(setHidden:YES)或者透明(alpha值为0)也不会收事件。不过这个属性只对视图有效,如果想要整个程序都步响应事件,可以调用UIApplication的beginIngnoringInteractionEvents方法来完全停止事件接收和分发。通过endIngnoringInteractionEvents方法来恢复让程序接收和分发事件。

如果要让视图接收多点触摸,需要设置它的multipleTouchEnabled属性为YES,默认状态下这个属性值为NO,即视图默认不接收多点触摸。

iPhone键盘改变颜色

只有这2种数字键盘才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

keyboardAppearance = UIKeyboardAppearanceAlert

代码如下:

NSArray *ws =[[UIApplication sharedApplication] windows];

for(UIView *w in ws){

NSArray *vs = [w subviews];

for(UIView *v in vs){

if([[NSStringstringWithUTF8String:object_getClassName(v)]isEqualToString:@"UIKeyboard"]){

v.backgroundColor= [UIColor redColor];

}

}

}

从一个界面push到下一界面左上角返回按钮文字设置

在父viewController中如下设置:

UIBarButtonItem*backbutton = [[UIBarButtonItem alloc]init];

backbutton.title= @"返回列表";

self.navigationItem.backBarButtonItem= backbutton;

[backbuttonrelease];

navigationbar的back键触发其他事件

UIButton *back=[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)];

[back addTarget:selfact

ion:@selector(reloadRowData:)forControlEvents:UIControlEventTouchUpInside];

[backsetImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];

UIBarButtonItem*backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];

self.navigationItem.leftBarButtonItem= loginButtonItem

[back release];

[backButtonItemrelease];

//防止屏幕暗掉锁屏

[[UIApplicationsharedApplication] 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];

[UIViewbeginAnimations:nil context:touchPointValue];

transform =CGAffineTransformMakeScale(0.1,0.21);

firstPieceView.transform= transform;

[UIView commitAnimations];

截取屏幕图片

//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)

UIGraphicsBeginImageContext(CGSizeMake(200,400));

//renderInContext 呈现接受者及其子范围到指定的上下文

[self.view.layerrenderInContext: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:[UIImageimageNamed:@"0006.png"]];

cell.selectedBackgroundView = myview;

点击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

每次输入都知道

[textViewbecomeFirstResponder]

(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=[NSTimerscheduledTimerWithTimeInterval:(3.0) target:self selector:@selector(addEnemy)userInfo:nil repeats:YES];

可以尝试使用一个单独的线程来实现

iphone中的UITouch

手指在屏幕上能达到的精度和鼠标指针有很大的不同。当用户触击屏幕时,接触

区域实际上是椭圆形的,而且比用户想像的位置更靠下一点。根据触摸屏幕的手指、手指的尺寸、手指接触屏幕的力量、手指的方向、以及其它因素的不同,

其“接触部位”的尺寸和形状也有所不同。底层的多点触摸系统会分析所有的这些信息,为您计算出单一的触点。

UIResponder是所有响应者对象的基类,

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

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch*touch = [touches anyObject];

NSUIntegernumTaps = [touch tapCount];

if(numTaps < 2) {

[self.nextRespondertouchesBegan:touches withEvent:event];

}else {

[selfhandleDoubleTap: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)、触摸对象的创建或最后一次变化发生在什么时间(timestamp)、以及触摸处于什么阶段(phase)。

-(void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{

UITouch*touch = [touches anyObject];

if([touch tapCount] == 2) {

CGPointtapPoint = [theTouch locationInView:self];

//Process a double-tap gesture

}

}

在touchesEnded:withEvent:方法中,当触击次数为一时,响应者对象就向自身发送一个performSelector:withObject:afterDelay:消息,其中的选择器标识由响应者对象实现的、用于处理单击手势的方法;第二个参数是一个NSValue 或NSDictionary对象,用于保存相关的UITouch 对象;时延参数则表示单击和双击手势之间的合理时间间隔。

在touchesBegan:withEvent:方法中,如果触击次数为二,响应者对象会向自身发送一个cancelPreviousPerformRequestsWithTarget:消息,取消当前被挂起和延期执行的调用。如果触碰次数不为二,则在指定的延时之后,先前步骤中由选择器标识的方法就会被调用,以处理单击手势。

C语言中&与&&的区别?

&& 是逻辑运算符,最终答案只能是1或者是0,  或者说是 true 或false. && 是逻辑与运算符,参加判断的两个条件有一个为0(就是假命题),那结果就是0;&是按位与(AND)运算符,与二进制存储和操作有关

多点触摸:

-(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开发-NSRunLoop概述和原理

1.什么是NSRunLoop?我们会经常看到这样的代码:

-       (IBAction)start:(id)sender{

pageStillLoading = YES;

[NSThread detachNewThreadSelector:@selector(loadPageInBackground:)toTarget:selfwithObject:nil];

[progress setHidden:NO];

while (pageStillLoading) {

[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopModebeforeDate:[NSDate distantFuture]];

}

[progress setHidden:YES];

}

这段代码很神奇的,因为他会“暂停”代码运行,而且程序运行不会因为这里有一个while循环而受到影响。在[progresssetHidden:NO]执行之后,整个函数像暂停了一样,停在循环里面,等loadPageInBackground里面的操作都完成了以后,才让 [progress setHidden:YES]运行。这样做就显得简单,而且逻辑很清晰。如果不这样做,就需要在loadPageInBackground里面表示load完成的地方调用[progresssetHidden: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"

@implementationMyTask

-(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-2509:44:45.393 OperationDemo[20676:1803] 开始线程=<MyTask: 0x4b4dea0>

2011-07-2509:44:45.393 OperationDemo[20676:5d03] 开始线程=<MyTask: 0x4b50db0>

2011-07-2509:44:45.396 OperationDemo[20676:1803] 开始线程=<MyTask: 0x4b51070>

2011-07-2509:44:45.404 OperationDemo[20676:6303] delloc mytask=<MyTask:0x4b4dea0>

2011-07-2509:44:45.404 OperationDemo[20676:5d03] delloc mytask=<MyTask:0x4b50db0>

2011-07-2509:44:45.405 OperationDemo[20676:6303] delloc mytask=<MyTask: 0x4b51070>

可以看到,根本没有执行NSTimer中的方法,线程就释放掉了,我们要执行

NSTimer中的方法,就要利用NSRunLoop阻塞线程。下面是修改后的代码:

-(void)main    {

NSLog(@"开始线程=%@",self);

NSTimer *timer=[NSTimer timerWithTimeInterval:2 target:selfselector:@selector(hiandeTime) userInfo:nilrepeats:NO];

[timer fire];

while (!didDisconnect) {

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]];

}      }

执行结果如下:

2011-07-2510:07:00.543 OperationDemo[21270:1803] 开始线程=<MyTask: 0x4d16380>

2011-07-2510:07:00.543 OperationDemo[21270:5d03] 开始线程=<MyTask:0x4d17790>

2011-07-2510:07:00.550 OperationDemo[21270:6303] 开始线程=<MyTask: 0x4d17a50>

2011-07-2510:07:00.550 OperationDemo[21270:1803] 执行了NSTimer

2011-07-2510:07:00.551 OperationDemo[21270:5d03] 执行了NSTimer

2011-07-2510:07:00.552 OperationDemo[21270:6303] 执行了NSTimer

2011-07-2510:07:00.556 OperationDemo[21270:6503] delloc mytask=<MyTask:0x4d16380>

2011-07-2510:07:00.557 OperationDemo[21270:6303] delloc mytask=<MyTask:0x4d17790>

2011-07-2510: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 = [NSURLURLWithString:@"http://www.baidu.com"];

ASIHTTPRequest*request = [ASIHTTPRequest requestWithURL:url];

[request start];

NSError *error =[request error];

if (!error) {

NSString*response = [request responseString];

}

当你需要添加更多的请求信息时,如,添加个请求Header:

[requestaddRequestHeader:@"name" value:@"Jory lee"];

添加Post请求时的健值:

[requestsetPostValue:@"Ben" forKey:@"first_name"];

[requestsetPostValue:@"Copsey" forKey:@"last_name"];

[requestsetFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

设置HTTP的授权帐号:

[requestsetUsername:@"username"];

[requestsetPassword:@"password"];

一个异步请求:

-(IBAction)grabURLInBackground:(id)sender{

NSURL *url = [NSURLURLWithString:@"http://allseeing-i.com"];

ASIHTTPRequest*request = [ASIHTTPRequest requestWithURL:url];

[requestsetDelegate:self];

[requeststartAsynchronous];

}

-(void)requestFinished:(ASIHTTPRequest *)request{

// Use whenfetching text data

NSString*responseString = [request responseString];

// Use when fetchingbinary data

NSData *responseData= [request responseData];

}

-(void)requestFailed:(ASIHTTPRequest *)request{

NSError *error =[request error];

}

在我们数据获取的过程中,如果数据源复杂,一个请求队列是必不可少的:

-(IBAction)grabURLInTheBackground:(id)sender{

if (![self queue]) {

[selfsetQueue:[[[NSOperationQueue alloc] init] autorelease]];

}

NSURL *url = [NSURLURLWithString:@"http://allseeing-i.com"];

ASIHTTPRequest*request = [ASIHTTPRequest requestWithURL:url];

[requestsetDelegate:self];

[requestsetDidFinishSelector:@selector(requestDone:)];

[requestsetDidFailSelector:@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正在进行的任务.

[self performSelector:@selector(addShrinkImg)withObject:self afterDelay:2.0f];//performSelector: withObject:afterDelay://线程的使用  延迟函数

View的层次结构

IPhoneView层次结构说明

View层次结构说明:

1.容器类,加强其他视图的功能,或提供额外的显示效果。

如:UIScrollView是用来显示那些内容太多,不能在一屏里显示的视图的;

UITableView是UIScrollView的子类,用来展现列表形式的内容的,因为表中的行是可选的,

UITableView也被用于层次结构的导航。

UIToolBar是用来显示一个或多个与按钮相似的子项,通常UIToolBar显示在屏幕底部,用来

显示一组经常使用的命令按钮。UIToolBar可以一直显示着,也可以在需要的时候才显示。

2.控件类,控件是用来创建应用程序的典型UI.控件都继承于UIControl,控件通常用来显示一个特定的值,

并处理与修改这个值相关的用户交互。控件使用标准的系统设计模式,如Target-Action和Delegation,

当用户发生交互时,通知应用程序。

包括:按钮UIButton,文本字段UITextField,滑块UISlider,和开关UISwitch。

3.显示类,只是用来显示,不提供交互。

包括:UIImageView,UILabel,UIProgressView,UIActivityIndicatorView

4.文本和网页类,用来显示多行文本。

如:UITextView支持多行的滚动显示与编辑。

UIWebView可以用来显示Html,这样就极大的丰富了展示效果,可以按照自定义方式显示文本。

5.警告UIAlertView和行动表UIActionSheet,警告和行动表用来迅速获取用户的注意力,给用户提示一些信息,

并附带一些选项,用户可以通过这些选项来相应信息。

功能上来说,这两个View是相似的,但是从外观和行为上来说就不一样了

UIAlertView是在屏幕中弹出蓝色背景的警告框

UIActionSheet是在屏幕底部滑出的。

6.导航类,标签栏UITabBar和导航栏UINavigationBar结合视图控制器让用户从一个视图转到另一个视图。

通常你并不需要创建他们的items,而是通过controller或者是Inerface Builder来配置他们。

7.窗口,窗口是其他View的根视图。典型的情况下是一个应用只有一个窗口。

loadView:

(加载视图)

- 建立层次结构

- 在不使用 Interface Builder 的时候发生

viewDidLoad:

(视图已加载)

- 加载附加的资源和数据

viewWillAppear:

(视图快要被显示)

- 准备在屏幕上加载

- 视图不会在每次显示重新加载

viewDidAppear:

(视图已被显示)

- 动画和其他视觉元素被加载

地图动画效果 (见附件)    //52楼

Objective-C基础:BOOL值的不同

布尔值

宏定义 真为YES 假为NO

Objective-C中的BOOL实际上是一种对带符号的字符类型(signedchar)的定义(typedef),它使用8位存储空间,YES定义为1,而NO定义为0(使用#define)。

Objective-C并不将BOOL作为仅能保存YES或NO值的真正的布尔类型来处理。编译器将BOOL认作8位二进制数,YES和NO值只是一种约定。

这引发了一个小问题:如果不小心将一个长于1字节的整型值(例如short或int值)赋给一个BOOL变量,那么只有低位字节会用作BOOL值。

假设该低位字节刚好为0(例如8960,写成十六进制0x2300),BOOL值将会是0,即NO值。

BOOL

在其大多数历史阶段,C都缺乏一个定义的布尔类型。它通过计算表达式来确定真值。如果一个表达式计算为0,则被认为是假;相反,则为真。

C99标准添加了一个布尔类型,bool,并且还添加了真值true和假值false。Objective-C有自己的布尔类型,BOOL,并且还有真值常量YES和假值常量NO。

BOOL不是一个基本类型。它是无符号的char的一个typedef(别名)。YES和NO只是为1和0定义的常量。

由于Objective-C继承了所有的C类型,因此我们可以在自己的Objective-C程序中使用bool类型。

然而,Cocoa框架和大多数已有的Objective-C代码使用BOOL。尽管可以在bool和BOOL之间相互转换,除非你的程序用到的库使用了bool,否则干脆忘掉bool会更容易一些。

注意  尽管Objective-C当前的版本是基于C99标准的,但Objective-C最初只是作为缺乏布尔类型的一个较早版本的C的扩展而开发的。

尽管C99的bool类型也可以使用,但大多数Objective-C社群使用Objective-C的BOOL。

SEL

SEL是保存了一个Objective-C方法名表示的一种类型。SEL是selector的缩写。方法名有时候叫做选择器,因为运行时使用它们来选择要执行的代码,以响应一条消息。

IMP

IMP是一个typedef,用于“一个指针,它指向接受参数id、SEL及可能的其他参数并且返回id的函数”。

BOOL和bool的区别

1、类型不同  

BOOL为int型  bool为布尔型  

2、长度不同 

bool只有一个字节  

BOOL长度视实际环境来定,一般可认为是4个字节

3、取值不同  

bool取值false和true,是0和1的区别; false可以代表0,但true有很多种,并非只有1。 

 如果数个bool对象列在一起,可能会各占一个bit,这取决于编译器。 

 BOOL是微软定义的typedef int BOOL(在windef.h中)。

布尔型变量bool

bool是布尔型变量,也就是逻辑型变量的定义符,类似于float,double等,只不过float定义浮点型,double定义双精度浮点型。

在objective-c中提供了相似的类型BOOL,它具有YES值和NO值。 布尔型变量的值只有 真 (true) 和假 (false)。

 布尔型变量可用于逻辑表达式,也就是“或”“与”“非”之类的逻辑运算和大于小于之类的关系运算,逻辑表达式运算结果为真或为假。  

 bool可用于定义函数类型为布尔型,函数里可以有 return TRUE; return FALSE 之类的语句。

 布尔型运算结果常用于条件语句,  

 if (逻辑表达式)  {   

      如果是 true 执行这里;

}

else {

     如果是 false 执行这里;   

};

BOOL在iphone程序开发中很重要,一般配合if语句进行判断,处理程序中逻辑关系!

if 语句与布尔值

if 语句是 C++/C 语言中最简单、最常用的语句,然而很多程序员用隐含错误的方式

写 if 语句。

假设布尔变量名字为 flag,它与零值比较的标准 if 语句如下:

if (flag) // 表示 flag 为真

if (!flag) // 表示 flag 为假

其它的用法都属于不良风格,例如:

if (flag == TRUE)

if (flag == 1 )

if (flag == FALSE)

if (flag == 0)

BOOL,int,float,指针变量 与“零值”比较的if语句

分别给出BOOL,int,float,指针变量 与“零值”比较的 if 语句(假设变量名为var)

解答:

BOOL型变量:if(!var)

int型变量: if(var==0)

float型变量:

const float EPSINON = 0.00001;

if ((x >= - EPSINON) && (x <= EPSINON)

指针变量:  if(var==NULL)

剖析:

考查对0值判断的“内功”,BOOL型变量的0判断完全可以写成if(var==0),而int型变量也可以写成if(!var),指针变量的判断也可以写成if(!var),

上述写法虽然程序都能正确运行,但是未能清晰地表达程序的意思。一般的,如果想让if判断一个变量的“真”、“假”,应直接使用if(var)、if(!var),表明其为“逻辑”判断;

如果用if判断一个数值型变量(short、int、long等),应该用if(var==0),表明是与0进行“数值”上的比较;而判断指针则适宜用if(var==NULL),这是一种很好的编程习惯。

浮点型变量并不精确,所以不可将float变量用“==”或“!=”与数字比较,应该设法转化成“>=”或“<=”形式。如果写成if (x ==0.0),则判为错,得0分。

IPhone之NSXMLParser的使用

NSXMLParser解析xml格式的数据 用法如下:

首先,NSXMLParser必须继续NSXMLParserDelegate协议

@interface XMLHelper :NSObject<NSXMLParserDelegate>

首先设置XML数据,并初始化NSXMLParser

- (void)viewDidLoad {

NSMutableString*Strxml=[NSMutableStringstringWithString:@"<Body><xml1>11111111</xml1><xml2><xml3>3333333333</xml3></xml2></Body>"];

NSData *data=[NSData dataWithBytes:[StrxmlUTF8String]length:[Strxml length]];

NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];//设置XML数据

[parser setShouldProcessNamespaces:NO];

[parser setShouldReportNamespacePrefixes:NO];

[parser setShouldResolveExternalEntities:NO];

[parser setDelegate:self];

[parser parse];

[super viewDidLoad];    }  //遍例xml的节点

- (void)parser:(NSXMLParser*)parser didStartElement:(NSString*) elementNamenamespaceURI:(NSString*)namespaceURIqualifiedName:(NSString*)qName attributes:(NSDictionary*)attributeDict {

NSLog(@"Name:%@",elementName);

}

//当xml节点有值时,则进入此句

-(void)parser:(NSXMLParser*)parserfoundCharacters:(NSString*)string

{    NSLog(@"Value:%@",string);    }

//当遇到结束标记时,进入此句

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*) elementName namespaceURI:(NSString*)namespaceURIqualifiedName: (NSString*)qName{

}  我的*****:213681048

如何使用SBJson

Json是一种类似XML的数据传输方式。详细介绍请看:介绍JSON

SBJson是与Objective-C结合比较好的库。

使用SBJson的文件需包含JSON.h头文件。

id jsonObject = [jsonString JSONValue];

此句创建json对象,JSONValue自动将json字符内容初始化为json对象。当然先需要将json文件内容读取为字符串。jsonObject可能是NSDictionary或NSArray。具体根据json内容。

json内容被SBJson转换为Objective-C的类型的方式如下:

Null -> NSNull

String -> NSMutableString

Array -> NSMutableArray

Object -> NSMutableDictionary

Boolean -> NSNumber

Number -> NSDecimalNumber

Iphone利用JSON传递数据,展示在Table界面中

下面是一个最简单的例子。效果如图:

上面用到了json传递的数据,有关json部分,iphone sdk虽然没有支持,但是第三方已经写好了。

json 参考:http://code.google.com/p/json-framework/

下面是具体的代码实现:

数据加载:

#import “MyDataSource.h”

#import “JSON.h”

@implementation MyDataSource

+ (NSDictionary *)fetchLibraryInformation{

NSString *urlString = [NSString stringWithFormat:@"http://wangjun.easymorse.com/wp-content/video/hello.jison"];

NSURL *url = [NSURL URLWithString:urlString];

NSLog(@”fetching library data”);

return [self fetchJSONValueForURL:url];

}

+ (id)fetchJSONValueForURL:(NSURL *)url{

NSString *jsonString =[[NSString alloc] initWithContentsOfURL:url

encoding:NSUTF8StringEncoding error:nil];

id jsonValue = [jsonString JSONValue];

[jsonString release];

return jsonValue;

}

@end

table数据展示:

#import “JSONTableTestViewController.h”

#import “MyDataSource.h”

@implementation JSONTableTestViewController

@synthesize myData;

- (void)viewDidLoad {

NSLog(@”加载数据“);

myData = [[MyDataSource fetchLibraryInformation] retain];

}

- (void)didReceiveMemoryWarning {

// Releases the view if it doesn’t have a superview.

[super didReceiveMemoryWarning];

// Release any cached data,images, etc that aren’t in use.

}

- (void)viewDidUnload {

// Release any retained subviewsof the main view.

// e.g. self.myOutlet = nil;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

return [myData count]; //有多少个section,也就是“几家”

}

-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {

return [[myData valueForKey:[[myData allKeys] objectAtIndex:section]] count];

//这里我们需要告诉UITableViewController每个section里面有几个,也就是“一家里面有几口人”

}

- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier= @”Cell”;

UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault

reuseIdentifier:CellIdentifier] autorelease];

}//上面的东西都是重复白给的,平时没事不用想为什么,照抄就可以了

cell.textLabel.text =[[myData valueForKey:[[myData allKeys] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

//这句看上去复杂,但是其实不过是在特定section里面找到对应的array,

//然后在array中找到indexPath.row所在的内容

return cell;

}

- (NSString *)tableView:(UITableView *)tableViewtitleForHeaderInSection:(NSInteger)section{

return [[myData allKeys] objectAtIndex:section];

//这里设置对应section的名字,很简单allKey返回所有的键值为一个array,也就是“张家”,“李家”

//然后用objectAtIndex: 来找出究竟是哪一个就可以了!

}

- (void)dealloc {

[myData release];

[super dealloc];    } @end

线程同步和线程异步有什么区别?(重要基础知识)

打个比方,如果你在等一个人,

同步的时候,你会一直等到她来了之后才做其他事情,这个过程除了等待你啥都不会做,

异步的时候,你一边在等,可能一边玩游戏或者是看报纸什么的,一直到她到来,你的等待状态才会结束

在实现上,同步的过程会阻塞进程的所有其他操作,将同步转换为异步的最常见方法则是

将会阻塞进程的等待操作放入到一个新的进程中,同时为该等待操作添加一个监视器,在检测到等待操作完成的时候结束等待的进程。

在tableview索引中显示搜索符号的方法

代码如下,在UITableViewDataSource中设置

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView{

NSMutableArray *arr= [[[NSMutableArray alloc] initWithCapacity:0] autorelease];

[arraddObject:@"{search}"];//等价于[arr addObject:UITableViewIndexSearch];

return arr;

}效果图:

MapKit学习笔记

1、概述

插入MapView,设置Delegate(一般为Controller),Annotations记录兴趣位置点(AnnotationView用来显示兴趣位置点),annotation是可选的,选中的annotation会显示callout,用来显示信息。

2、设置地图显示类型:

mapView.mapType =MKMapTypeStandard;

mapView.mapType =MKMapTypeSatellite;

mapView.mapType =MKMapTypeHybrid;

3、显示用户位置

设置为可以显示用户位置:

mapView.showsUserLocation= YES;

判断用户当前位置是否可见(只读属性):

userLocationVisible

得到用户位置坐标:当userLocationVisible为YES时

CLLocationCoordinate2Dcoords = mapView.userLocation.location.coordinate;

4、坐标范围

MKCoordinateRegion用来设置坐标显示范围。

包括两部分:Center(CLLocationCoordinate2D struct,包括latitude和longitude),坐标中心

和Span(MKCoordinateSpan struct,包括latitudeDelta和longitudeDelta),缩放级别

MKCoordinateRegionviewRegion = MKCoordinateRegionMakeWithDistance(center,2000, 2000);

以上代码创建一个以center为中心,上下各1000米,左右各1000米得区域,但其是一个矩形,不符合MapView的横纵比例

MKCoordinateRegionadjustedRegion = [mapView regionThatFits:viewRegion];

以上代码创建出来一个符合MapView横纵比例的区域

[mapViewsetRegion:adjustedRegion animated:YES];

以上代码为:最终显示该区域

5、Delegate

使用MapView须符合MKMapViewDelegate协议

5.1、地图加载Delegate

当需要从Google服务器取得新地图时

mapViewWillStartLoadingMap:

当成功地取得地图后

mapViewDidFinishLoadingMap:

当取得地图失败后(建议至少要实现此方法)

mapViewDidFailLoadingMap:withError:

5.2、范围变化Delegate

当手势开始(拖拽,放大,缩小,双击)

mapView:regionWillChangeAnimated:

当手势结束(拖拽,放大,缩小,双击)

mapView:regionDidChangeAnimated:

判断坐标是否在MapView显示范围内:

CLLocationDegreesleftDegrees = mapView.region.center.longitude–(mapView.region.span.longitudeDelta / 2.0);

CLLocationDegreesrightDegrees = mapView.region.center.longitude+(mapView.region.span.longitudeDelta / 2.0);

CLLocationDegreesbottomDegrees = mapView.region.center.latitude–(mapView.region.span.latitudeDelta / 2.0);

CLLocationDegreestopDegrees = self.region.center.latitude +(mapView.region.span.latitudeDelta /2.0);

if (leftDegrees >rightDegrees) { // Int'l Date Line in View

leftDegrees = -180.0- leftDegrees;

if (coords.longitude> 0) // coords to West of Date Line

coords.longitude =-180.0 - coords.longitude;

}

If (leftDegrees<= coords.longitude && coords.longitude <= rightDegrees&& bottomDegrees <= coords.latitude && coords.latitude <=topDegrees) {

// 坐标在范围内

}

6、Annotation

Annotation包含两部分:Annotation Object和Annotation View

Annotation Object必须符合协议MKAnnotation,包括两个方法:title和subtitle,分别用于显示注释的标题和子标题。还有coordinate属性,返回CLLocationCoordinate2D,表示Annotation的位置

然后,需使用mapView:viewForAnnotation:方法来返回MKAnnotationView或者MKAnnotationView的子类用来显示Annotation(注意:这里显示的不是选中Annotation后的弹出框)

你可以子类化MKAnnotationView,然后再drawRect:方法里面进行自己的绘制动作(这个方法很蠢)

你完全可以实例化一个MKAnnotationView,然后更改它的image属性,这样很简单。

7、添加移除Annotation

添加一个Annotation

[mapView addAnnotation:annotation];

添加一个Annotation数组

[mapViewaddAnnotations:[NSArray arrayWithObjects:annotation1, annotation2, nil]];

移除一个Annotation

removeAnnotation:

移除一个Annotation数组

removeAnnotations:

移除所有Annotation

[mapViewremoveAnnotations:mapView.annotations];

8、选中Annotation

一次只能有一个Annotation被选中,选中后会出现CallOut(浮动框)

简单的CallOut显示Title和SubTitle,但你也可以自定义一个UIView作为CallOut(与自定义的TableViewCell一样)

可通过代码选中Annotation:

selectAnnotation:animated:

或者取消选择:

deselectAnnotation:animated:

9、显示Annotation

通过mapView:viewForAnnotation:方法显示Annotation,每在MapView中加入一个Annotation,就会调用此方法

示例(与tableView:cellForRowAtIndexPath:很相似)

- (MKAnnotationView*) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {

static NSString*placemarkIdentifier = @"my annotation identifier";

if ([annotationisKindOfClass:[MyAnnotation class]]) {

MKAnnotationView*annotationView = [theMapViewdequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];

if (annotationView== nil) {

annotationView =[[MKAnnotationView alloc] initWithAnnotation:annotationreuseIdentifier:placemarkIdentifier];

annotationView.image= [UIImage imageNamed:@"blood_orange.png"];

}

else

annotationView.annotation= annotation;

returnannotationView;

}

return nil;

}

10、取得真实地址

示例:

初始化MKReverseGeocoder

MKReverseGeocoder*geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinates];

geocoder.delegate =self;

[geocoder start];

如果无法处理坐标,则调用reverseGeocoder:didFailWithError:方法

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError*)error {

NSLog(@"Errorresolving coordinates: %@", [error localizedDescription]);

geocoder.delegate =nil;

[geocoderautorelease];

}

如果成功,则调用reverseGeocoder:didFindPlacemark:并把信息存储在MKPlacemark 中

didFindPlacemark:(MKPlacemark*)placemark {

NSString*streetAddress = placemark.thoroughfare;

NSString *city =placemark.locality;

NSString *state =placemark.administrativeArea;

NSString *zip =placemark.postalCode;

// Do something withinformation

geocoder.delegate =nil;

[geocoder autorelease];

}

Leaves-- iOS上一种图书翻页效果的实现

Leaves是由Tow Brow开发的一个简单的图书翻页控件,它巧妙地结合了镜像层、阴影层(用于半透明页)和渐变层(用于阴影)来实现图书的翻页效果。其翻页效果如下图所示:

特性

Leaves支持:

文本、图像、PDF等任何可被渲染到Graphics Context上的对象

通过拖动或点击来翻页

支持ipad和iphone大小的显示区域

Levels目前不支持以下特性

页面上的交互元素

轻扫动作

类和接口

Leaves中主要有三个类:LevelsView、LevelsViewController、LevelsCache:

LevelsCache:是一个辅助类,用于缓存显示页。它将显示的内容缓存为图片并保存。

LevelsView:是翻页视图,翻页的主要效果便在些实现。它定义了一系列的层对象,并通过操作这些层对象来实现翻页中各种效果。

LevelsViewController: LevelsView的控制器

类似于UITableView, LevelsView也有一个相关的数据源类(LeaveViewDataSource)与委托类(LeavesViewDelegate),它们分别有两个方法,如下所示

复制代码

@protocolLeavesViewDataSource <NSObject>

- (NSUInteger)numberOfPagesInLeavesView:(LeavesView*)leavesView;

- (void)renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx;

@end

@protocolLeavesViewDelegate <NSObject>

@optional

- (void)leavesView:(LeavesView *)leavesViewwillTurnToPageAtIndex:(NSUInteger)pageIndex;

- (void)leavesView:(LeavesView *)leavesView didTurnToPageAtIndex:(NSUInteger)pageIndex;

@end

层树结构

LevelsView中的层树结构如下图所示:

每一个层(Layer)都有其特殊的用途,或作为内容的显示层,或作为阴影层,具体说明如下:

topPage层:显示当前页的内容。

topPageOverlay层:在翻页过程中,该层覆盖于topPage层上,且颜色偏暗,从而使topPage未翻转的部分变暗,有阴影的感觉。

topPageShadow层:在翻页过程中,该层用于表达topPage被翻转部分所形成的阴影。

topPageReverse层:翻页过程中,topPage被翻转部分的反面的容器层。

topPageReverseImage层:反面的内容页。在竖屏下,用于显示topPage被翻转部分的内容,这些内容被映射到该层,给人感觉书是透明的。在横屏下,显示的是下一页的内容。

topPageReverseOverlay层:该层用于覆盖topPageReverse层,效果与topPageOverlay类似。

topPageReverseShading层:该层在topPageReverse层右侧形成一个阴影。

bottomPage层:topPage页的下一页所在的层。

bottomPageShadow层:该层为在翻页过程中在 bottomPage左侧形成的一个阴影层。

leftPage层:该层为横屏模式下左侧页所在的层。

leftPageOverlay层:该层覆盖于为 leftPage层,效果与topPageOverlay类似。

由上可以看出,层树中的层主要分为三类:

内容显示层:topPage、topPageReverseImage、bottomPage、leftPage

阴影层:topPageShadow、topPageReverseShading、bottomPageShadow

覆盖层:topPageOverlay、topPageReverseOverlay、leftPageOverlay

图片缓存

Tow Brow在处理不同的内容(文本、图像、PDF)时显示时,所采取的方法是一样的。他将内容缓存为图像,并显示在屏幕上。基本方法是将内容写进CGContextRef中,然后根据CGContextRef中的信息创建图像,具体方法如下:

复制代码

-(CGImageRef)imageForPageIndex:(NSUInteger)pageIndex {

CGColorSpaceRefcolorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context =CGBitmapContextCreate(NULL,

pageSize.width,

pageSize.height,

8, /* bits percomponent*/

pageSize.width * 4,/* bytes per row */

colorSpace,

kCGImageAlphaPremultipliedLast| kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);

CGContextClipToRect(context,CGRectMake(0, 0, pageSize.width, pageSize.height));

[dataSourcerenderPageAtIndex:pageIndex inContext:context];

CGImageRef image =CGBitmapContextCreateImage(context);

CGContextRelease(context);

[UIImageimageWithCGImage:image];

CGImageRelease(image);

return image;

}

当然程序没有缓存所有页的内容,而是根据横竖屏的不同缓存适当数量的内容。每次翻页时会重新整理缓存中的内容。翻页动画实现。

在Leaves中,翻页的基本原理其实很简单:翻页过程中,根据手指的划动来不断的调整层树结构中每个层的frame,翻页结束后,重新调整内容显示层所显示的内容。

为此,LevelsView中设置了一个leafEdge变量,该变量是手指在屏幕上划动时TouchPoint在屏幕x轴上的百分比位置,这个操作在touchesMoved:withEvent中完成:

复制代码

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

......

UITouch *touch =[event.allTouches anyObject];

CGPoint touchPoint =[touch locationInView:self];

[CATransactionbegin];

[CATransactionsetValue:[NSNumber numberWithFloat:0.07]

forKey:kCATransactionAnimationDuration];

self.leafEdge =touchPoint.x / self.bounds.size.width;

[CATransactioncommit];

}

而在leafEdge的set方法中,我们根据leafEdge的值来重新设定各个Layer的frame属性

复制代码

- (void)setLayerFrames {

CGRectrightPageBoundsRect = self.layer.bounds;

CGRect leftHalf,rightHalf;

CGRectDivide(rightPageBoundsRect,&leftHalf, &rightHalf, CGRectGetWidth(rightPageBoundsRect) / 2.0f,CGRectMinXEdge);

if (self.mode ==LeavesViewModeFacingPages) {

rightPageBoundsRect= rightHalf;

}

topPage.frame =CGRectMake(rightPageBoundsRect.origin.x,

rightPageBoundsRect.origin.y,

leafEdge *rightPageBoundsRect.size.width,

rightPageBoundsRect.size.height);

topPageReverse.frame= CGRectMake(rightPageBoundsRect.origin.x + (2*leafEdge-1) *rightPageBoundsRect.size.width,

rightPageBoundsRect.origin.y,

(1-leafEdge) *rightPageBoundsRect.size.width,

rightPageBoundsRect.size.height);

......}

最后便是当手指离开屏幕时,如何处理翻页结果(将当前页翻过去还是没有翻过去)。这个操作在 这个操作在touchesEnded:withEvent中完成

复制代码

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

......

UITouch *touch =[event.allTouches anyObject];

CGPoint touchPoint =[touch locationInView:self];

BOOL dragged =distance(touchPoint, touchBeganPoint) > [self dragThreshold];

[CATransactionbegin];

float duration;

if ((dragged&& self.leafEdge < 0.5) || (!dragged && [selftouchedNextPage])) {

[selfwillTurnToPageAtIndex:currentPageIndex + numberOfVisiblePages];

self.leafEdge = 0;

duration = leafEdge;

......

}

else {

[selfwillTurnToPageAtIndex:currentPageIndex];

self.leafEdge = 1.0;

duration = 1 -leafEdge;

.......

}

[CATransactionsetValue:[NSNumber numberWithFloat:duration]

forKey:kCATransactionAnimationDuration];

[CATransactioncommit];

}

如果需要在翻页后执行某些操作(如在屏幕上显示当前页数等),则可以在继承自LevelsViewController的控制器中实现leavesView:didTurnToPageAtIndex方法。

在此需要注意的就是topPageReverseImage在竖屏时做了如下的变换

复制代码

topPageReverseImage.contentsGravity= kCAGravityRight;

topPageReverseImage.transform= CATransform3DMakeScale(-1, 1, 1);

从而使topPageReverseImage显示的内容让人感觉是透过纸张,看到topPage的内容。

横屏与竖屏

Leaves还有一个特点就是其支持横屏时,能同时看到两页的内容(该效果是由OleBegemann改进的)。该改进最关键的地方就是增加了leftPage层,同时在横屏显示时将屏幕一分为二,在左侧显示leftPage。同进在翻页的过程中,topPageReverseImage显示的是topPage页下一页的内容。在翻转屏幕时,会根据方向重新调整内容的显示。

图片放大缩小的区域点击事件代码例子

比如我们有个中国地图,在北京这个区域放了一个button,当这张地图放大和缩小的时候,我们都能点击这个button触发北京里面的事件。

// ImplementviewDidLoad to do additional setup after loading the view, typically from anib.

- (void)viewDidLoad{

[super viewDidLoad];

x= 1;

y= 1;

UIImage *image = [UIImage imageNamed:@"index_big.jpg"];

imageView = [[UIImageView alloc] initWithImage:image];

imageView.frame = CGRectMake(0, 0, 1024, 768);

imageView.userInteractionEnabled = YES;

scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 1024, 768)];

scrollView.contentSize = CGSizeMake(imageView.frame.size.width,imageView.frame.size.height);

scrollView.maximumZoomScale = 3.0;

scrollView.minimumZoomScale = 1.0;

scrollView.delegate = self;

[self.view addSubview:scrollView];

[self.view bringSubviewToFront:scrollView];

[scrollView addSubview:imageView];

[scrollView bringSubviewToFront:imageView];

}

-(void)viewDidAppear:(BOOL)animated {

[super viewDidAppear:YES];

uaButton= [UIButton buttonWithType:UIButtonTypeCustom];

uaButton.frame = CGRectMake(731*x, 235*y, 130, 60);

[uaButton setTag:1];

[uaButton addTarget:self action:@selector(clickButton:)forControlEvents:UIControlEventTouchUpInside];

[imageView addSubview:uaButton];

}

#pragma mark -

#pragma mark viewzoom

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {

return imageView;

}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView*)view atScale:(float)scale{

NSLog(@"scrollViewDidEndZooming  width:%f,height:%f",imageView.frame.size.width, imageView.frame.size.height);

x= imageView.frame.size.width/1024;

y= imageView.frame.size.height/768;

}

刷新 view 时不全屏加载的方法

如果你的 iPhne应用里涉及到刷新功能,但不需要全屏加载去覆盖老的 view,而只是刷新部分屏幕(比如,320×400的面积),可以先在 view 中添加 一个 320×400 的 view。再将 navigationController.view 加入到这个 320×400 的 view 中,再用这个 navigationController 去刷新的 viewController 就可以了。

代码例子 TestPush.zip

iPhonetable 实现动态加载图片的教程

iPhone在加载列表时,如果每个等待把所有列表中的数据都加载完在显示相关内容,如果列表中有一些比较大的图片,加载的时间比较长,那么给用户的效果就很差了,下面详细是一种实现动态加载图片的办法:

- (UITableViewCell*)tableView:(UITableView *)tableView

cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell* cell = [tableViewdequeueReusableCellWithIdentifier:@"tag"];

if (cell==nil) {

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle

reuseIdentifier:@"tag"] autorelease];

}

//表格设计

NSDictionary* one = [array objectAtIndex:indexPath.row];

cell.textLabel.text = [one objectForKey:@"title"];

cell.detailTextLabel.text = [one objectForKey:@"content"];

[NSThread detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:)toTarget:self withObject:indexPath];

return cell;

}

-(void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

UIImage *image = [self getImageForCellAtIndexPath:indexPath];

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

[cell.imageView performSelectorOnMainThread:@selector(setImage:)withObject:image waitUntilDone:NO];

[imagerelease];

[pool release];

}

-(UIImage*)getImageForCellAtIndexPath:(NSIndexPath *)indexPath {

id path = [[array objectAtIndex:indexPath.row]objectForKey:@"image"];

NSURL *url = [NSURL URLWithString:path];

NSData *data = [NSData dataWithContentsOfURL:url];

UIImage *image = [[UIImage alloc] initWithData:data cache:NO];

return image;

}

关于TableView中图片的延时加载

经常我们会用tableView显示很多条目, 有时候需要显示图片, 但是一次从服务器上取来所有图片对用户来浪费流量, 对服务器也是负担.最好是按需加载,即当该用户要浏览该条目时再去加载它的图片。

重写如下方法

- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell *)cellforRowAtIndexPath:(NSIndexPath *)indexPath{

UIImage*image = [self getImageForCellAtIndexPath:indexPath];  //从网上取得图片

[cell.imageViewsetImage:image];

}

这虽然解决了延时加载的问题, 但当网速很慢, 或者图片很大时(假设,虽然一般cell中的图很小),你会发现程序可能会失去对用户的响应.

原因是UIImage *image = [selfgetImageForCellAtIndexPath:indexPath]; 这个方法可能要花费大量的时间,主线程要处理这个method.

所以失去了对用户的响应.

所以要将该方法提出来:

-(void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath{

NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];

UIImage*image = [self getImageForCellAtIndexPath:indexPath];

UITableViewCell*cell = [self.tableView cellForRowAtIndexPath:indexPath];

[cell.imageViewperformSelectorOnMainThread:@selector(setImage:) withObject:imagewaitUntilDone:NO];

[poolrelease];

}

然后再新开一个线程去做这件事情

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

[NSThreaddetachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:selfwithObject:indexPath];

}

同理当我们需要长时间的计算时,也要新开一个线程 去做这个计算以避免程序处于假死状态

以上代码只是示例, 还可以改进的更多, 比如从网上down下来一次后就将图片缓存起来,再次显示的时候就不用去下载。

提高iPhoneapp里图片加载速度的方法

加载多张小图片,要比加载一张由上述小图组成的大图片耗费更多的时间。而且考虑到iPhone图片的内存占用,一张像素129*129的小图片和256*256的大图片相比,内存消耗一样多。所以您可以要求美工把横、纵排的小图多多合成为大图,尽量减少文件数量,这样大量文件加载的速度会有所提升。

多张图片整合成连续动画的代码

把多张图片整合成连续动画,这恐怕是很多苹果开发者需要的功能。下面是单次播放和循环播放的代码。

animationImageView.animationImages= imageFrames;// imageFrames 是一个图片数组  animationImageView是一个imageview

[UIViewsetAnimationDelegate:self];

animationImageView.animationDuration= 0.75f;

animationImageView.animationRepeatCount= 3;

[animationImageViewstartAnimating];

shouldPlay = NO;

NSInteger timeout =3;

[NSTimer scheduledTimerWithTimeInterval:timeouttarget:self selector:@selector(stopAnimation) userInfo:nil repeats:NO];

循环播放的代码

UIImageView*animView= [[UIImageView alloc] initWithFrame:self.view.frame];

animView.animationImages = [NSArray arrayWithObjects:

[UIImage imageNamed:@"01.gif"],

[UIImage imageNamed:@"02.gif"],

[UIImage imageNamed:@"03.gif"],nil];

// all frames will execute in 1.75 seconds

animView.animationDuration = 1.75;

// repeat the annimation forever

animView.animationRepeatCount = 0;

// start animating

[animView startAnimating];

// add the animation view to the main window

[self.view addSubview:animView];

iPhone的动画效果类型及实现方法

实现iphone漂亮的动画效果主要有两种方法,一种是UIView层面的,一种是使用CATransition进行更低层次的控制,

第一种是UIView,UIView方式可能在低层也是使用CATransition进行了封装,它只能用于一些简单的、常用的效果展现,这里写一个常用的示例代码,供大家参考。

viewplaincopy to clipboardprint?

1.[UIView beginAnimations:@"Curl"context:nil];//动画开始

2.[UIView setAnimationDuration:0.75];

3.[UIView setAnimationDelegate:self];

4.[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:myview cache:YES];

5.[myview removeFromSuperview];

6.[UIView commitAnimations];

[UIViewbeginAnimations:@"Curl"context:nil];//动画开始[UIView setAnimationDuration:0.75];[UIView setAnimationDelegate:self];[UIViewsetAnimationTransition:UIViewAnimationTransitionCurlUp forView:myviewcache:YES];[myview removeFromSuperview];[UIView commitAnimations];

第二种方式相对复杂一些,但如果更好的进行控制,还是使用这种方法吧,基本使用方法可以看一下如下例子:

viewplaincopy to clipboardprint?

1.CATransition *animation = [CATransition animation];

2.[animation setDuration:1.25f];

3.[animation setTimingFunction:[CAMediaTimingFunction

4.functionWithName:kCAMediaTimingFunctionEaseIn]];

5.[animation setType:kCATransitionReveal];

6.[animation setSubtype: kCATransitionFromBottom];

7.[self.view.layer addAnimation:animation forKey:@"Reveal"];

CATransition*animation = [CATransition animation];[animation setDuration:1.25f];[animationsetTimingFunction:[CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseIn]];[animationsetType:kCATransitionReveal];[animation setSubtype:kCATransitionFromBottom];[self.view.layer addAnimation:animationforKey:@"Reveal"];

这里使用了setType与setSubtype组合,这使用个比较保险,因为他的参数就是官方API里定义的,他们的参数说明可以参考如下:

viewplaincopy to clipboardprint?

1.setType:可以返回四种类型:

2.kCATransitionFade淡出

3.kCATransitionMoveIn覆盖原图

4.kCATransitionPush推出

5.kCATransitionReveal底部显出来

6.setSubtype:也可以有四种类型:

7.kCATransitionFromRight;

8.kCATransitionFromLeft(默认值)

9.kCATransitionFromTop;

10.        kCATransitionFromBottom

setType:可以返回四种类型:kCATransitionFade淡出kCATransitionMoveIn覆盖原图kCATransitionPush推出kCATransitionReveal底部显出来setSubtype:也可以有四种类型:kCATransitionFromRight;kCATransitionFromLeft(默认值)kCATransitionFromTop;kCATransitionFromBottom

还有一种设置动画类型的方法,不用setSubtype,只用setType

viewplaincopy to clipboardprint?

1.[animation setType:@"suckEffect"];

[animationsetType:@"suckEffect"];

这里的suckEffect就是效果名称,可以用的效果主要有:

viewplaincopy to clipboardprint?

1.pageCurl   向上翻一页

2.pageUnCurl 向下翻一页

3.rippleEffect 滴水效果

4.suckEffect 收缩效果,如一块布被抽走

5.cube 立方体效果

6.oglFlip 上下翻转效果

pageCurl  向上翻一页pageUnCurl 向下翻一页rippleEffect 滴水效果suckEffect 收缩效果,如一块布被抽走cube 立方体效果oglFlip上下翻转效果

最后再给出一种常用代码供大家参考。

viewplaincopy to clipboardprint?

1.// Curl the image up or down

2.CATransition *animation = [CATransition animation];

3.[animation setDuration:0.35];

4.[animation setTimingFunction:UIViewAnimationCurveEaseInOut];

5.if (!curled){

6.//animation.type = @"mapCurl";

7.animation.type = @"pageCurl";

8.animation.fillMode = kCAFillModeForwards;

9.animation.endProgress = 0.99;

10.        } else {

11.        //animation.type = @"mapUnCurl";

12.        animation.type = @"pageUnCurl";

13.        animation.fillMode = kCAFillModeBackwards;

14.        animation.startProgress = 0.01;

15.        }

16.        [animation setRemovedOnCompletion:NO];

17.        [view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];

18.        [view addAnimation:animation forKey"pageCurlAnimation"];

19.        // Disable user interaction where necessary

20.        if (!curled) {

21.

22.        } else {

23.

24.        }

25.        curled = !curled;

// Curl the image up or downCATransition *animation =[CATransition animation];[animation setDuration:0.35];[animationsetTimingFunction:UIViewAnimationCurveEaseInOut];if (!curled){//animation.type= @"mapCurl";animation.type =@"pageCurl";animation.fillMode =kCAFillModeForwards;animation.endProgress = 0.99;} else {//animation.type =@"mapUnCurl";animation.type =@"pageUnCurl";animation.fillMode = kCAFillModeBackwards;animation.startProgress= 0.01;}[animation setRemovedOnCompletion:NO];[view exchangeSubviewAtIndex:0withSubviewAtIndex:1];[view addAnimation:animationforKey"pageCurlAnimation"];// Disable user interaction wherenecessaryif (!curled) { } else { }curled = !curled;

Xcode4主题推荐:Zenburn Theme

 

长久对着 Xcode 写代码,默认 Theme的白亮和高对比度让我的眼睛很疲倦。自带的 Midnight Theme 太艳俗,而且对比度依然很高。我在 Emacs 里用Zenburn,感觉不错,于是就自己动手 port 到 Xcode里,并针对性的做了微调。暗色系,低对比度,适合长时间编码,喜欢的话,可从GitHub 上获取。演示效果如下图:

iPad软件提交注意事项

根据自己的iPad软件提交经验总结的注意事项,希望大家留意一下,避免软件被苹果审核人员拒绝放行。

肯定会被拒的情况:

1. app命名:不要用类似*** pad的名字,但可以用***for iPad,*** iPad version之类的名字;

2. popover相关:

a. 除非处于任务编辑状态,popover应该随时可以通过点他范围之外的地方来dismiss掉,换句话说,不要用modal方式;

b. 不要太大,宽度不要超过600;

c.pickerview啥的一定要放在popover里面,宽度不要拉长

d.alertview也要用popover的方式出来

3. 尽量不要使用全屏切换效果(我用了flip导致被拒,不知道curl行不行),好像一定要用全屏的话,可以用modal的方式,这一点我也理解的不是很明 白;

不会导致被拒但是建议改进的:

1. 尽量支持4个方向

2. 少用alertview和全屏视图切换

3.尽量多用ipad相关的UIelement,popover,splitview啥的

总的感觉,苹果审核比较注重要体现出他和iPhone App的不同之处,以及保证用户体验的流畅性。

iPad软件界面设计基本规范

iPad平台特点

1 大屏幕,分辨率 1024x768

2 再次强调没有固定的方向,必须四个方向都支持。

3 可以外接键盘

4 可以放置设备,与台式机同步

iPhone与iPad的共同特点

- 内存有限

- 同时运行单个程序

- 在设置功能里放置程序选项

- 设备方向可以改变

- 最小化的帮助,让用户直接就能看懂

- 程序响应手势而不是鼠标

- 运行源生程序、Web程序或者二者兼备

- 图片深度24位(RGB各8位),另带8位alpha通道,建议使用PNG格式图片

界面简单建议

- 支持所有方向

注意要为每个方向都提供一个启动图片

- 增强交互而非只增加功能

- 使用split view, 导航和弹出窗口来平整信息层级

- 减少全屏切换,仅仅改变需要改变的部分

- 支持协作和互联

- 如果可能,增加真实感以及物理维度到应用程序里,尽可能像真实世界的物品以便用户易于上手

- 界面漂亮 用户喜爱

- 尽量让用户更关注内容而不是界面

- 尽可能减少强制用户模式化操作

- 减少使用列表,改变为其他形式

- 尽量支持多手指手势

- 让用户模式化操作的地方可以用弹出窗口

- 限制复杂的模式化操作

- 减小文件操作尤其尽量让用户感觉不到文件系统的存在

- 仅仅在必须的情况才提示用户保存

- 将工具条整合在界面上部

- 尽可能快速启动程序

尽量使用截图作为启动画面

不要在启动时显示关于或者splashscreen

恢复上次运行状态

尽量不要让用户提供设置信息

- 程序可能随时停止

- 为每个方向都准备启动画面

- 建立漂亮的图标

尺寸:72x72

和iPhone程序类似,iPad程序的图标会自动增加:圆角、阴影和高光。

图标标准:

> 90度直角边

> 没有高光

> 不带alpha通道透明

- 遵循已有规范

iPhone开发资源汇总   //75楼

http://www.cocoachina.com/iphonedev/toolthain/2011/1019/3387.html

我的*****:213681048

iphone程序的生命周期

 做iphone开发首先第一件就是得知道iphone程序的生命周期,说白点就是当点击程序图标启动程序开始到退出程序整个使用运行过程中底下的代码都发生了什么,只有理解了这个才能游刃有余的掌握Iphone程序的开发,否则在写程序的时候有点浑浑僵僵不知所以然的感觉。

多线程多任务HTTP下载代码分享

自己写了个多线程多任务HTTP下载的例子,感觉写得不是很好,另外下载JPG图片时偶尔会遇到

<ERROR> JPEGCorrupt JPEG data: premature end of data segment 问题,之前用异步的NSURLConnection

也遇到过这个问题,GOOGLE了很久没有找到合适的解决方法。请各位多多指教。

MultiDownloader.zip

Three20中TTNavigator用法总结

简单映射:

Three20中的TNavigator对于软件导航很有用,只需要维护一张map映射表就行了。就像url表示一个网页一样,Three20也采用了相同的方式,用url关联页面。大家可以参看TTNavigatorDemo中的源码:

TTURLMap* map =navigator.URLMap;

// Any URL thatdoesn't match will fall back on this one, and open in the web browser

[mapfrom:@"*" toViewController:[TTWebController class]];

// The tab barcontroller is shared, meaning there will only ever be one created. Loading

// This URL will makethe existing tab bar controller appear if it was not visible.

[mapfrom:@"tt://tabBar" toSharedViewController:[TabBarController class]];

// Menu controllersare also shared - we only create one to show in each tab, so opening

// these URLs willswitch to the tab containing the menu

[mapfrom:@"tt://menu/(initWithMenu:)"toSharedViewController:[MenuController class]];

上面的代码就是给页面注册url, 如tt:tabBar就表示TabBarController,只要调用TTOpenURL(@"tt://tabBar");这句代码就可以初始化TabBarController,并显示出来。相当于执行了TabBarController *test=[[TabBarController alloc] init];[self.view addSubview:test.view];

如果调用TTOpenURL(@"tt://menu/1");会发生什么? 它会调用MenuController中的

-(id)initWithMenu:(MenuPage)page {

if (self = [superinit]) {

self.page = page;

}

return self;

}

为什么会调用这个方法呢? 因为我们在上面map的时候是用的tt://menu/(initWithMenu:)括号里是方法名,可以想像成如果有括号,那么它就表示一变量,那么它就是一对多的映射, 与数学上的映射一个道理。,tt://menu/1tt://menu/2 tt://menu/3 ..... tt://menu/XXX 都表示这个对应, 所以TTOpenURL(@"tt://menu/2");的时候也会调用上面的方法。

而这个1,2,3 ....XXX就表未参数传入到上面这个方法。为什么会样呢,因为这是Three20的规则。还有注意,你的MenuController必须要实现

-(id)initWithMenu:(MenuPage)page

这个方法,不然就不能达到效果。 在map映射的时候,如果加括号有方法名的时候,这个方法返回的必须是Controller. (这是我的理解,不知道正确与否,知道的大侠通知我一下)

多参数映射:

上面的情况是只有一个参数转入,如果想传多个参数如何办呢?我知道有两种方法:

1. 将映射改为:

[mapfrom:@"tt://menu/(initWithMenu:)/(withParam:)"toSharedViewController:[MenuController class]];

这样就可以传入两个参数,相应的方法就应改为:

-(id)initWithMenu:(MenuPage)page withParam:(NSString*)param {

if (self = [superinit]) {

self.page = page;

}

return self;

}

2。将映射改为:

[mapfrom:@"tt://menu?menu=(initWithMenu:)"toSharedViewController:[MenuController class]];

这种方式也可以传入多个参数,如:TTOpenURL(@"tt://menu?menu=1&ref=hello&name=world&phone=123");这样就传入了三个参数,

那么它的初始化方法就应写为:

-(id)initWithMenu:(MenuPage)page query:(NSDictionary*)query {

NSString *ref =[query objectForKey:@"ref"];

NSString *name =[query objectForKey:@"name"];

NSString *phone =[query objectForKey:@"phone"];

if (self = [superinit]) {

self.page = page;

}

return self;

}

注意:如果

-(id)initWithMenu:(MenuPage)page

这个方法与上面多参数方法同时存在的话, 那么首先是调用上面这个单参数方法,并没有智能的根据参数的不同而选择初始化方法,避免错误调用方法就是在映射的时候将方法名命名为不同的名字。

Hash URL

在demo中有一个Hash URL的例子,它可以指定方法的调用。

如果将MenuController里的代码修改一下:

self.navigationItem.rightBarButtonItem=

[[[UIBarButtonItemalloc] initWithTitle:@"Order" style:UIBarButtonItemStyleBordered

target:@"tt://order?waitress=Betty&ref=toolssssstest#param"

action:@selector(openURLFromButton:)]autorelease];

那么点order的时候就会调用ContentController里的

-(void)orderAction:(NSString*)action {

TTDPRINT(@"ACTION:%@", action);

}

因为map映射的是:

[mapfrom:@"tt://order?waitress=(initWithWaitress:)"toModalViewController:[ContentController class]];

[mapfrom:@"tt://order?waitresss=()#(orderAction:)"toViewController:[ContentController class]];

好了,就些就是我学习的一点点小结,可能有误 ,望大家指正。

参考:

http://three20.pypt.lt/url-based-navigation-and-state-persistence

http://three20.info/article/2010-10-06-URL-Based-Navigation

http://www.slideshare.net/iphonedevbr/three20

原文链接:http://blog.csdn.net/favormm/article/details/6760533

常用16种视图切换动画小结

前4种是UIView,后面都是 CoreAnimation,

下面8种是传说中的私有API

整合到一个例子里,代码较清晰,适合新手阅读,效果如下图:

源码下载: StudyiOS.zip

iPhone开发 地图线路

因为接触到了这么一个项目,所以进行了这个功能的深入了解,比较忙,所以把关键代码贴在这里,如果有问题,请留言。

效果图如下:可能有偏移,这里不进行解决。

用到的几个方法代码如下:

使用google地图 api 3.0协议解析两个经纬度,得到行进路线。

比较重要的一个方法:}

这个是基本的绘制线路的方法。最后生成一张图片。

地图居中显示

#pragma mark mapViewdelegate functions

-(void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{

route_view.hidden =YES;

}

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{

[selfupdate_route_view];

route_view.hidden =NO;

[route_viewsetNeedsDisplay];

}http://www.cocoachina.com/iphonedev/sdk/2011/1031/3437.html

CoverFlow基本原理及Tapku实现方法

Cover Flow是苹果首创的将多首歌曲的封面以3D界面的形式显示出来的方式。如下图所示:

从图中可以看到,显示在中间的图片为目标图片,两侧的图片在y轴都旋转了一定的角度,并且每两张图片之间都保持了一定的距离。在交互(如点击两侧的图片)的时候,滑动到中间的图片会逐渐放大,旋转的角度由原来的旋转角度a变为0,且位置上移动中间,变成新的目标图片;同时原处于中间位置的图片则缩小、旋转一定的角度、位置偏移到一侧。所以在整个过程中,主要有两个属性发生了变化:角度与位置(缩放只是视觉上的,并没有进行缩放操作)。

在每次点击一张图片时,如果这张图片在目标图片的左边,则所有的图片都会向右移动,同时做相应的旋转;相反,点击目标图片右侧的图片时,所有图片都会向左移动并做相应的旋转。

从如上描述的效果,可以看出在CoverFlow中最主要的的操作有两个:3D仿射变换与动画。仿射变换实质上是一种线性变换,通常主要用到的仿射变换有平移(Translation)、旋转(Rotation)、缩放(Scale)。

对于这两种操作,iOS都提供了非常简便的接口来实现。接下来我们便以tapku的实现方法为例,来说明实现CoverFlow的基本过程。

一、图片的布局

从效果图可以看出,图片是按一条直接排列,图片与图片之间有一定的间距,目标图片是正向显示,两侧的图片则按一定的角度进行了旋转,与目标图片形成一定的角度。同时我们还能看到每个图片都有一个倒影,并且这个倒影是渐变的,由上而下逐渐透明度逐渐减小。

1、 Cover Flow单元的定义

在tapku中,每一个图片附属于一个视图(TKCoverflowCoverView),这个视图相当于UITableViewCell,它包含了三个要素:图片(imageView),倒影图片(reflected),渐变层(gradientLayer)。渐变层覆盖于倒影图片上,且大小位置一致。

TKCoverflowCoverView的声明及布局代码如下所示:

复制代码

@interfaceTKCoverflowCoverView : UIView {

float baseline;

UIImageView*imageView;

UIImageView*reflected;

CAGradientLayer*gradientLayer;

}

@end

-(id)initWithFrame:(CGRect)frame {

self = [superinitWithFrame:frame];

if (self) {

self.opaque = NO;

self.backgroundColor= [UIColor clearColor];

self.layer.anchorPoint= CGPointMake(0.5, 0.5);

imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width,self.frame.size.width)];

[selfaddSubview:imageView];

reflected =[[UIImageView alloc] initWithFrame:CGRectMake(0, self.frame.size.width,self.frame.size.width, self.frame.size.width)];

reflected.transform= CGAffineTransformScale(reflected.transform, 1, -1);

[self addSubview:reflected];

gradientLayer =[CAGradientLayer layer];

gradientLayer.colors= [NSArray arrayWithObjects:(id)[UIColor colorWithWhite:0alpha:0.5].CGColor,(id)[UIColor colorWithWhite:0 alpha:1].CGColor,nil];

gradientLayer.startPoint= CGPointMake(0, 0);

gradientLayer.endPoint= CGPointMake(0, 0.4);

gradientLayer.frame= CGRectMake(0, self.frame.size.width, self.frame.size.width,self.frame.size.width);

[self.layeraddSublayer:gradientLayer];

}

return self;

}

注意:此次将视图的锚点(anchorPoint属性)设置为(0.5,0.5),即视图的中心点,目的是让视图以中心点为基点进行旋转。

在进行仿射变换时,视图作为一个整体进行变换。

2、图片的布局

tapku中,图片的布局与交互是在TKCoverflowView类中完成的。类TKCoverflowView继承自UIScrollView,相当于是TableView。

该类中定义是两个仿射变量:

复制代码

CATransform3DleftTransform, rightTransform

这两个变量分别设置了两侧图片的仿射变换,具体的设置方法为

复制代码

- (void) setupTransforms{

leftTransform =CATransform3DMakeRotation(coverAngle, 0, 1, 0);

leftTransform =CATransform3DConcat(leftTransform,CATransform3DMakeTranslation(-spaceFromCurrent,0, -300));

rightTransform =CATransform3DMakeRotation(-coverAngle, 0, 1, 0);

rightTransform =CATransform3DConcat(rightTransform,CATransform3DMakeTranslation(spaceFromCurrent,0, -300));

}

其中coverAngle为旋转的角度。对每个仿射变量同时设置了旋转也平移变换。

Cover Flow单元是存储在一个数组中:

复制代码

NSMutableArray*coverViews;

初始化时设置数组的大小,并存入空对象。在后期获取某个索引位置的单元时,如果该单元为空,则生成一个新的TKCoverflowCoverView并放入相应位置。

复制代码

if([coverViewsobjectAtIndex:cnt] == [NSNull null]){

TKCoverflowCoverView*cover = [dataSource coverflowView:self coverAtIndex:cnt];

[coverViewsreplaceObjectAtIndex:cnt withObject:cover];

......

}

每个CoverFlow单元的位置计算如下

复制代码

CGRect r =cover.frame;

r.origin.y =currentSize.height / 2 - (coverSize.height/2) - (coverSize.height/16);

r.origin.x =(currentSize.width/2 - (coverSize.width/ 2)) + (coverSpacing) * cnt;

cover.frame = r;

其中currentSize,coverSize,coverSpacing都是固定值。从中可以看出所有单元的y值都是一样的,而x值则与其在数组中的索引值相关,索引越大,x值也越大。而这就涉及我们之后的一个问题。一会再讲。

假定目标图片的索引为currentIndex,则目标图片两侧的仿射属性设置如下:

复制代码

if(cnt >currentIndex){

cover.layer.transform= rightTransform;

}

else

cover.layer.transform= leftTransform;

如上即为CoverFlow的基本布局,可以与UITableView比较一下。

二、交互

Cover Flow的基本交互是点击两侧的图片,则被点击的图片成为新的目标图片并移动中屏幕中间,而其它图片一起移动,在这个过程中所需要做的就两件事:旋转与平移。

方法很简单:在动画块中重新设置CoverFlow单元的transform属性,这样就可以缓动实现这个动画的过程。实际上只有新旧目标图片及中间的图片需要做这种变换,其余图片的transform属性都是不变的。

复制代码

float speed = 0.3;

[UIViewbeginAnimations:string context:nil];

[UIViewsetAnimationDuration:speed];

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseOut];

[UIViewsetAnimationBeginsFromCurrentState:YES];

[UIViewsetAnimationDelegate:self];

[UIViewsetAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

for(UIView *v inviews){

int i = [coverViewsindexOfObject:v];

if(i < index)v.layer.transform = leftTransform;

else if(i >index) v.layer.transform = rightTransform;

elsev.layer.transform = CATransform3DIdentity;

}

[UIViewcommitAnimations];

但这在做的只是旋转了CoverFlow的内容,并没有对Cover Flow进行水平平移,Cover Flow水平位置已由其origin.x值固定。那么水平上的平移是如何实现的呢,我们看下面的代码:

复制代码

- (void)snapToAlbum:(BOOL)animated{

UIView *v =[coverViews objectAtIndex:currentIndex];

if((NSObject*)v!=[NSNullnull]){

[selfsetContentOffset:CGPointMake(v.center.x - (currentSize.width/2), 0)animated:animated];

}else{

[selfsetContentOffset:CGPointMake(coverSpacing*currentIndex, 0) animated:animated];

}

}

其所做的就是以目标图片为中心,整体平移TKCoverflowView视图。

三、总结

由上可以看出,CoverFlow特效的原理很简单:对新旧目标图片及中间的图片以动画的形式做仿射变换。至于仿射变换如何处理,有不同的方法。tapku所实现的方法可以说相对简单灵活。

Android, Flash都有类似的Cover Flow特效实现方法,有兴趣的童鞋可以参考一下。

原帖地址:http://www.cocoachina.com/bbs/read.php?tid-75699-fpage-2.html

iPhoneOS 4发现视频会议和聊天功能

此前有不少传闻都在猜测第四代iPhone会不会拥有前置摄像头,因为视频通话功能已经成为3G网络 的基本应用支持,iPhone用户也在期待苹果公司会在手机中加入这项服务。来自9to5mac网站的报道,在苹果最新公布的iPhoneOS 4.0系统中发现了关于视频会议、视频聊天室等功能代码,再次印证了下一代iPhone将配备牵涉摄像头的说法。

此前在3.1版SDK中曾发现有视频会议相关信息,虽然苹果公司后来取消了这个功能,但是在新版的系统中该功能再次出现,本次发现的代码内容包括聊 天室、主持人、视频会议和加密功能,让开发者可以制作视频聊天游戏等应用。

首先是在conference.framework文件夹中发现了关于输入视频聊天请求的提示音,经播放发现该声音与iChat应用的提示音一样。

在CoreLocalizable.strings下面你可以看到视频、聊天室、主持人等加密字符串。

iPhone的视频会议将包括一对一视频聊天和多人视频电话会议。

此外苹果公司还在测试iPhone的视频会议服务,并开启了一个服务器,该服务器目前已经对外开放测试。

UIWebView之获取所点位置图片URL

UIWebView有自己的UIResgure,如果我们手动加入自己的GestureRecognize将不能识别,如UILongPressGestureRecongnizer. 在浏览网页的时候,如果看到喜欢的图片,想把它保存下来如何办呢? 我们可以自己写一个程序来实现,用uiwebview开发一个自己的浏览器。

关面说到uiwebview不能识别long press gesture,幸好有一个可以识别,那就是double click.因此我们注册它,代码如下:

UITapGestureRecognizer*doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(doubleTap:)];

doubleTap.numberOfTouchesRequired= 2;

[self.theWebViewaddGestureRecognizer:doubleTap];

然后就是实现doubleTap:

-(void) doubleTap:(UITapGestureRecognizer*) sender {

// <Find HTML tagwhich was clicked by user>

// <If tag isIMG, then get image URL and start saving>

int scrollPositionY= [[self.theWebView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"]intValue];

int scrollPositionX= [[self.theWebViewstringByEvaluatingJavaScriptFromString:@"window.pageXOffset"]intValue];

int displayWidth =[[self.theWebViewstringByEvaluatingJavaScriptFromString:@"window.outerWidth"]intValue];

CGFloat scale =theWebView.frame.size.width / displayWidth;

CGPoint pt = [senderlocationInView:self.theWebView];

pt.x *= scale;

pt.y *= scale;

pt.x +=scrollPositionX;

pt.y +=scrollPositionY;

NSString *js =[NSString stringWithFormat:@"document.elementFromPoint(%f,%f).tagName", pt.x, pt.y];

NSString * tagName =[self.theWebView stringByEvaluatingJavaScriptFromString:js];

if ([tagName isEqualToString:@"img"]){

NSString *imgURL =[NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src",pt.x, pt.y];

NSString *urlToSave= [self.theWebView stringByEvaluatingJavaScriptFromString:imgURL];

NSLog(@"imageurl=%@", urlToSave);

}

}这样我们就可以得到图片的url,然后下载保存就行了。

利用ASIHTTPRequest发送数据到(新浪微博)以及新浪API Oauth认证

利用ASIHTTPRequest发送数据到Sina Weibo

Oauth_Sina weiboOauth.zip新浪API认证,只要改Key.h就行了,把里面的APPKEY 和APPSECRET改成你在新浪申请的就应用APPKey

然后导入真机开始认证(必须有WIFI),运行App,会进入新浪网站要求你输入你的微博帐号和密码进行认证,认证完成后,把OAuthConsumerKey与kOAuthConsumerSecret记下来

附件2:testPost_SinaWeibo.zip我写的一个测试Demo,SDK3.0测试Ok

只要把WeiBoData.h头文件里面的宏定义kOAuthConsumerKey和kOAuthConsumerSecret改成以上你所记录下来的你自己应用的kOAuthConsumerKey和kOAuthConsumerSecret

然后修改WeiBoData.m的-(void)getUserInformation函数,如果你未登入过帐号,这里先填写你的,帐号和密码

-(void)getUserInformation{

NSUserDefaults*userInformation= [NSUserDefaultsstandardUserDefaults];

username =[userInformation valueForKey:@"userName"];

password =[userInformation valueForKey:@"userPwd"];

if([username length]< 1 && [password length] <1){

//别看了,就这里。。

username=@"";

password=@"";

}

}

PS:感谢Qd哥,大老晚的帮忙测试解决了一点 问题。(发送图片,路径那里,[request setData:imageData forKey:@"pic"];)@"pic"我一直用的@"picture"与@"Photo"再测试。。。。就没想到@"Pic"..我都汗了。。

[url=job.php?action=download&aid=17969]Oauth_Sina weibo Oauth.zip[/url]

[url=job.php?action=download&aid=17970]testPost_SinaWeibo.zip[/url]

http://www.cocoachina.com/bbs/read.php?tid-38804.html

利用DTGridView实现横向滚动的tableview

我们都知道tableview的实现原理,就是创建当前可见个数的tablecell,滚动过程中只是更改不可见的tablecell到可见的位置并且更新数据。这样可以避免滚动很多屏不用创建相应的视图,这样就不会造成内存泄漏。下面是实现的效果图:

下面是实现的代码:

#pragma markDTGridViewDataSource Methods

-(NSInteger)numberOfRowsInGridView:(DTGridView *)gv {

return 1;

}

-(NSInteger)numberOfColumnsInGridView:(DTGridView *)gvforRowWithIndex:(NSInteger)index {

return 20;

}

-(CGFloat)gridView:(DTGridView *)gv heightForRow:(NSInteger)rowIndex {

returngv.frame.size.height;

}

-(CGFloat)gridView:(DTGridView *)gv widthForCellAtRow:(NSInteger)rowIndexcolumn:(NSInteger)columnIndex {

returngv.frame.size.width;

}

- (DTGridViewCell*)gridView:(DTGridView *)gv viewForRow:(NSInteger)rowIndex column:

(NSInteger)columnIndex{

returngv.frame.size.width;

}

- (DTGridViewCell*)gridView:(DTGridView *)gv viewForRow:(NSInteger)rowIndexcolumn:(NSInteger)columnIndex {

MyTableCell *cell =(MyTableCell *)[gv dequeueReusableCellWithIdentifier:@"cell"];

if (!cell) {

cell = [[[NSBundlemainBundle] loadNibNamed:@"MyTableCell" owner:self options:nil]objectAtIndex:0];

cell.identifier =@"cell";

}

[cell onShowCell];

return cell;

}

iCloud存储原理与部分操作

http://www.cocoachina.com/iphonedev/sdk/2011/1102/3443.html

WCF实现从mac系统到windows的跨平台 iPhone程序开发实现

由于对移动平台充满着好奇与兴趣,最近着手了iPhone开发和学习。学习的路线是从objective-c到cococa。方法是看了两本入门的英文书,还有就是学习apple的sdk。对于产品的基本想法是服务端用.net,手机客户端用iPhone。

一些复杂的逻辑处理放到服务端实现,客户端与服务端通过XML交互,在iPhone客户端解析XML通过cocoa展示数据。由于iPhone和DoNet是两个完全不同的平台。iPhone依靠mac系统平台,donet依赖windows系统平台。这篇文章我将通过一个hello world程序讲述一下通过WCF实现从mac系统到windows的跨平台的调用。

1、创建简单的WCF服务

服务契约代码如下:服务契约代码如下:实现如下:

2、在iPhone中调用WCF

与donet调用wcf服务不同,这里使用NSURLConnection去获取WCF服务端的数据,代码如下:

NSURLConnection的委托方法:

解析XML的中hello world的委托方法,对于objective-c解析xml可以看我的上一篇博客:运行:

总结:本文通过一个简单的例子,说明了iPhone调用WCF的方法。用wcf实现跨平台还是蛮简单的!

图像及动画处理二:百叶窗效果

图片切割这后就可以做百叶窗效果了让每片叶子动起来有两种动画方式scale和rotation

注:如果处理后的小图片能保存有它们在大图片中的rect时,小图片利用起来就特别方便   源码下载:LeavesLeaves

参考苹果对方法的命名的规范

我经常用的字段有如下:需要注意的一点就是,你存的是ID,还是FullName?还是Code 应该区分开来比较好。

ID:主键,每个实体都有他唯一的标识码,就像我们的身份证号码,一般建议采用单主键,好做外键,设置数据库主外键关联约束。

Code:编号,可以不输入,但是不能重复,我有时候会用程序判断,有时候会建立唯一索引,这样也自动不能重复了。

UserName:登录名,用数字或者拼音,登录时方便输入,例如“jirigala”。

FullName:姓名,这是真实的姓名,例如“吉日嘎拉”。

CompanyID:这个数据当时是归属于哪个公司的,因为员工是有可能换工作,调公司的。

DepartmentID:这个数据当时是归属于哪个部门的。

WorkgroupID:这个数据当时是归属于哪个工作组的。

StaffID:这个数据当时是归属于哪个员工的。

Enabled:数据是否已生效,很可能输入的数据经过审核后才会生效的。

DeleteMark:数据是否被删除了,我不能把数据真删了,那就找不回来了。

AuditStatus:审核状态,审核流程放在另外表里,只是状态,写在这个表里了,按严格来说,状态也不应该放在这个表里,应该放在工作流表里。

Description:设计的字段再多,也永远满足不了客户不断在变化的需求,多弄一个备注字段,所有放不下的,没地方放的内容,全部可以塞在这个字段里了,否则你就是设置1000个字段,可能会出现第10001个需求。SortCode:

CreateUserID:这个数据是谁创建的?把主键记录起来,因为直接记录姓名,可能会有姓名重复的可能性,例如在内蒙古我的名字重复的概率就高很多。

CreateUserRealname:创建人的姓名,虽然有些冗余,但是在列表里显示数据很方便,现在硬盘也大,冗余一些也无所谓。

CreateDate:这个数据是什么时候被建立的,出了事情还能知道是什么时候搞出来的,公安是非常重视,什么时候人被咔嚓了,最好是能详细到几点,在什么地点发生的。

ModifyUserID:谁修改了数据?

ModifyUserRealname:谁?

ModifyDate:什么时间修改的数据?

审核状态我一般分,若觉得哪里不妥或者命名有错的,我马上修改!

MBProgressHUD的使用

网上下载 MBProgessHUD 类,导入到工程。

https://github.com/jdg/MBProgressHUD2。#import "MBProgressHUD.h"

类实现 MBProgressHUDDelegate 代理。

在类里面定义: MBProgressHUD* progress_;

显示;view plain

progress_ = [[MBProgressHUD alloc] initWithView:self.tableView];  [self.view addSubview:progress_];  [self.view bringSubviewToFront:progress_];  progress_.delegate = self;  progress_.labelText = @"加载中...";  [progress_ show:YES];

隐藏:viewplain

if (progress_)   {      [progress_ removeFromSuperview];      [progress_ release];      progress_ = nil;  }

实现协议:viewplain

- (void)hudWasHidden:(MBProgressHUD *)hud   {      NSLog(@"Hud: %@", hud);      // Remove HUD from screen when the HUD was hidded    [progress_ removeFromSuperview];      [progress_ release];      progress_ = nil;  }

图像及动画处理三:WaitingBar

一个很简单的等待页面的等待条的制作,方法如下:

-(id)initWithFrame:(CGRect)aFrame color:(UIColor*)aColortimeInterval:(float)aInterval;

discussion:

arguments-

aFrame:视图框架,包括所有小球,其高为小球直径的2倍,宽与高的比值的2倍为小球的数量

aColor:小球颜色

aInterval:相邻小球跳动的时间间隔

return value:视图,包括所有小球

以上为公共参数,当然也可以根据需要,自行在方法体中进行更细致和专门的修改.效果如下图:

WaitingBar

iPhone开发笔记——webservice解析xml

给你一个我做过的案例吧是关于一个webservice的解析的关键市解析xml文件,在苹果底下没有现成的类将xml文件解析成树状的类,自己按照帮助文档的案例推敲吧!

#import"QQViewController.h"

@implementationQQViewController

@synthesizeqqCodeText;

@synthesizeqqStatusLabel;

@synthesize webData;

@synthesizesoapResults;

@synthesizexmlParser;

@synthesizerecordResults;

@synthesizeactivityIndicatorView;

//处理文字输入完毕键盘的隐藏 或者在输入完毕按回车时直接进行查询

-(IBAction)textDidEndExit:(id)sender{

//[qqCodeTextresignFirstResponder];

[senderresignFirstResponder];

}

- (void)getQQStatus{

recordResults=NO;

//soap requestmessage

NSString*soapMessage=[NSString stringWithFormat:

@"<?xml version="1.0"encoding="utf-8"?>\n"

"<soap:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">\n"

"<soap:Body>"

"<qqCheckOnlinexmlns="http://WebXml.com.cn/">"

"<qqCode>%@</qqCode>"

"</qqCheckOnline>"

"</soap:Body>"

"</soap:Envelope>",qqCodeText.text];

//请求地址

NSURL*url=[NSURLURLWithString:@"http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx"];

NSMutableURLRequest*theRequest=[NSMutableURLRequestrequestWithURL:url];

NSString*msgLegth=[NSString stringWithFormat:@"%d",[soapMessagelength]];

[theRequestaddValue:@"text/xml;charset=utf-8"forHTTPHeaderField:@"Content-Type"];

[theRequestaddValue:@"http://WebXml.com.cn/qqCheckOnline"forHTTPHeaderField:@"SOAPAction"];

[theRequestaddValue:msgLegthforHTTPHeaderField:@"Content-Length"];

[theRequestsetHTTPMethod:@"POST"];

[theRequestsetHTTPBody:[soapMessagedataUsingEncoding:NSUTF8StringEncoding ]];

//request

NSURLConnection*theConnection=[[NSURLConnection alloc]initWithRequest:theRequestdelegate:self];

//connection

if(theConnection){

webData=[[NSMutableDatadata]retain];

}else{

NSLog(@"theConnectionis NULL");

}

}

-(IBAction)selectStatus{

//qqStatusLabel.text=@"Gettingtime ...";

//等待界面

[activityIndicatorViewstartAnimating];

[qqCodeTextresignFirstResponder];//为什么在这里释放

[self getQQStatus];

}

-(void)didReceiveMemoryWarning {

// Releases the viewif it doesn't have a superview.

[superdidReceiveMemoryWarning];

// Release anycached data, images, etc that aren't in use.

}

-(void)viewDidUnload {

// Release anyretained subviews of the main view.

// e.g.self.myOutlet = nil;

self.qqCodeText=nil;

self.qqStatusLabel=nil;

[superviewDidUnload];

}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{

// Return YES forsupported orientations

return(interfaceOrientation ==UIInterfaceOrientationPortrait);

}

- (void)dealloc {

[qqCodeTextrelease];

[qqStatusLabelrelease];

[superdealloc];

}

//接受到数据

-(void)connection:(NSURLConnection*)connection   didReceiveData:(NSData *)data{

[webData appendData:data];

NSLog(@"connection didReceiveData:2");

}

//没有接受到数据

-(void)connection:(NSURLConnection*)connectiondidReceiveResponse:(NSURLResponse *)response{

NSLog(@"webdata length is :%d",[webData length]);

[webData setLength:0];

NSLog(@"connection:didReceiveResponse:1");

}

-(void)connection:(NSURLConnection*)connectiondidFailWithError:(NSError *)error{

NSLog(@"ERROR with theConnection");

[connection release];

[webData release];

}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection{

NSString *theXML=[[NSString alloc] initWithBytes:[webDatamutableBytes] length:[webData            length]encoding:NSUTF8StringEncoding];

[theXMLrelease];

if(xmlParser){

[xmlParser release];

}

xmlParser=[[NSXMLParseralloc] initWithData:webData];

[xmlParser setDelegate:self];

[xmlParser setShouldResolveExternalEntities:YES];

[xmlParser parse];

[connectionrelease];

}

-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURIqualifiedName:(NSString *)qName

attributes:(NSDictionary *)attributeDict{

if([elementName isEqualToString:@"qqCheckOnlineResult"]){

if(!soapResults){

soapResults=[[NSMutableString alloc] init];

}

recordResults=YES;

}

}

-(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string{

if(recordResults){

[soapResultsappendString:string];

}

}

//在这里接收到返回的数据

-(void)parser:(NSXMLParser*)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURIqualifiedName:(NSString *)qName{

if([elementNameisEqual:@"qqCheckOnlineResult"]){

recordResults=FALSE;

[activityIndicatorViewstopAnimating];

if([soapResultsisEqualToString:@"Y"]){

qqStatusLabel.text=[[[NSStringinit] stringWithFormat:@"%@ 状态是:",qqCodeText.text] stringByAppendingString:@"在线"];

}elseif([soapResults isEqualToString:@"N"]){

qqStatusLabel.text=[[[NSStringinit] stringWithFormat:@"%@ 状态是:",qqCodeText.text] stringByAppendingString:@"离线"];

}elseif([soapResults isEqualToString:@"E"]){

qqStatusLabel.text=[[[NSStringinit] stringWithFormat:@"%@ 状态是:",qqCodeText.text]stringByAppendingString:@"QQ号码错误"];

}elseif([soapResults isEqualToString:@"A"]){

qqStatusLabel.text=[[[NSStringinit] stringWithFormat:@"%@ 状态是:",qqCodeText.text] stringByAppendingString:@"商业用户验证失败"];

}elseif([soapResults isEqualToString:@"V"]){

qqStatusLabel.text=[[[NSStringinit] stringWithFormat:@"%@ 状态是:",qqCodeText.text] stringByAppendingString:@"免费用户超过数量"];

}

[soapResultsrelease];

soapResults=nil;

}

}

-(void)parserDidStartDocument:(NSXMLParser*)parser{

//解析开始

//[activityIndicatorView];

}

-(void)parserDidEndDocument:(NSXMLParser*)parser{

//解析完成

}

-(void)viewDidLoad{

[activityIndicatorViewstopAnimating];

[activityIndicatorViewhidesWhenStopped];

[super viewDidLoad];

}

@end

iphone开发之xml解析流程小结

解析xml文件是一个简单的过程,大体思路总结有如下几个步骤:

一、创建xml节点模型。创建模型是为了方便我们更好地对每个xml节点进行管理和操作。节点模型的自由度因人而异。

二、创建模型管理器。模型管理器管理所有的节点模型,是对节点模型的一个统一封装,主要的功能是提供给使用到xml数据的开发人员。

三、创建解析器。

解析器解析xml文件,并把数据初始化到每一个节点模型,并返回模型管理器对象。

图像及动画处理四:旋转等待条(仿苹果)

手写了仿苹果的旋转等待条,并可通过参数设置属性,方法如下:

-(id)initWithRadius:(float)aRadius color:(UIColor*)aColortimeInterval:(float)aInterval;

discussion-

arguments-

aRadius: 包含动画的正方形的半个边长,这个正方形的中心在0点(0,0).也可以认为是可视

区域的半径

aColor:小长条的颜色

aInterval:相邻小长条跳动的时间间隔

return value:UIView类型,中心在0点(0,0)

若有必要,可在方法体中进行进一步的修改

从效果上来看,与苹果等待条很像,但可放大缩小且不失真,效果如图:WaitingBar2

iOS5打开系统setting页面

iOS5的SDK现在可以直接打开setting页面了,以往的SDK则不可以,当时我还花了大量时间去实现,结果不了了之。

如果你想打开LocationServices的setting页面,代码如下:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];

如果想打开Twitter的设置:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]];

如果想打开蓝牙的设置:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General&path=Bluetooth"]];

当然你还可以打开应用的设置:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Apps&path=Your+App+Display+Name"]];

Your+App+Display+Name是什么,你应懂的。 不过我试这个的时候没有打开应用的setting,反而打开的是系统setting页,不知道为何。

使用UIActivityIndicatorView

UIActivityIndicatorView实例提供轻型视图,这些视图显示一个标准的旋转进度轮。当使用这些视图时,最重要的一个关键词是小。20×20像素是大多数指示器样式获得最清楚显示效果的大小。只要稍大一点,指示器都会变得模糊。图4-7显示了一个40像素的版本。

你需要在屏幕上将该指示器居中。将其放置在最方便操作的位置。作为背面清晰的视图,指示器将混合位于其后的背景视图。该背景的主要颜色帮助选择要使用的指示器样式。

对于一般用途,只需将活动指示器作为子视图添加到你要覆盖的窗口、视图、工具栏或导航栏。分配该指示器并使用一个框来初始化它,最好位于当前所使用的父视图中央。

通过将指示器的animating属性更新为YES来启动它。若要停止,将该属性设置为NO。Cocoa Touch会负责完成其余工作,在视图不使用时隐藏视图。

iPhone提供了几种不同样式的UIActivityIndicatorView类。UIActivityIndicator- ViewStyleWhite和UIActivityIndicatorViewStyleGray是最简洁的。黑色背景下最适合白色版本的外观,白色背景最适合灰色外观(如图4-7所示)。它非常瘦小,而且采用夏普风格。选择白色还是灰色时要格外注意。全白显示在白色背景下将不能显示任何内容。而UIActivityIndicatorViewStyleWhiteLarge只能用于深色背景。它提供最大、最清晰的指示器。秘诀4-6显示了创建这些简单的UIActivityIndicatorView实例的代码。

图4-7 UIActivityIndicatorView类提

供了一个简单的旋转轮,

这意味着将以相对较小的尺寸显示

向程序中添加UIActivityIndicatorView

UIActivityIndicatorView的两种形式

用法一:只显示不停旋转的进度滚轮指示器。

//显示进度滚轮指示器

-(void)showWaiting {

progressInd=[[UIActivityIndicatorViewalloc]initWithActivityIndicatorStyle:

UIActivityIndicatorViewStyleWhiteLarge];

progressInd.center=CGPointMake(self.view.center.x,240);

[self.navigationController.viewaddSubview:progressInd];

[progressIndstartAnimating];

}

//消除滚动轮指示器

-(void)hideWaiting {

[progressInd stopAnimating];   }

用法二:带有半透明背景的进度轮指示器。

//显示进度滚轮指示器

-(void)showWaiting:(UIView*)parent{

intwidth = 32, height = 32;

CGRectframe= CGRectMake(100,200, 110,70) ;//[parent frame]; //[[UIScreenmainScreen]applicationFrame];

int x= frame.size.width;

int y= frame.size.height;

frame= CGRectMake((x - width) / 2, (y - height) / 2, width, height);

UIActivityIndicatorView* progressInd =[[UIActivityIndicatorViewalloc]initWithFrame:frame];

[progressIndstartAnimating];

progressInd.activityIndicatorViewStyle =UIActivityIndicatorViewStyleWhiteLarge;

frame =CGRectMake((x -70)/2, (y - height) / 2 + height, 80, 20);

UILabel*waitingLable =[[UILabel alloc] initWithFrame:frame];

waitingLable.text=@"Loading...";

waitingLable.textColor=[UIColor whiteColor];

waitingLable.font=[UIFont systemFontOfSize:15];

waitingLable.backgroundColor=[UIColor clearColor];

frame= CGRectMake(100, 200, 110, 70) ;//[parentframe];

UIView*theView = [[UIView alloc] initWithFrame:frame];

theView.backgroundColor =[UIColor blackColor];

theView.alpha = 0.7;

[theView addSubview:progressInd];

[theViewaddSubview:waitingLable];

[progressInd release];

[waitingLablerelease];

[theView setTag:9999];

[parent addSubview:theView];

[theView release];

}

//消除滚动轮指示器

-(void)hideWaiting {

[[self.viewviewWithTag:9999]removeFromSuperview];

}

iphone网络post连接的两种处理方式(同步和异步)  

第一种: 直接返回方式。

-(void)UpadaPost:(NSString*)strcontext URL:(NSString *)urlstr{

NSLog(urlstr);

NSLog(strcontext);

assert(strcontext!= NULL);

assert(urlstr!= NULL);

NSData*postData = [strcontext dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];  

NSString*postLength = [NSString stringWithFormat:@"%d", [postDatalength]];  

NSMutableURLRequest*request = [[[NSMutableURLRequest alloc] init] autorelease];  

[requestsetURL:[NSURL URLWithString:urlstr]];  

[requestsetHTTPMethod:@"POST"];  

[requestsetValue:postLengthforHTTPHeaderField:@"Content-Length"];  

[requestsetValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];  

[requestsetHTTPBody:postData];  

 

NSURLResponse*respone;

NSError*error;

NSData*myReturn =[NSURLConnection sendSynchronousRequest:request returningResponse:&respone

error:error];

NSLog(@"%@",[[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]);

}

第二种,采用事件代理方式(重要)

使用TouchXML时,常用到下面的代码

-(void)UpadaPost:(NSString*)strcontext URL:(NSString *)urlstr{

NSLog(urlstr);

NSLog(strcontext);

assert(strcontext!= NULL);

assert(urlstr!= NULL);

NSData*postData = [strcontext dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];  

NSString*postLength = [NSString stringWithFormat:@"%d", [postDatalength]];  

NSMutableURLRequest*request = [[[NSMutableURLRequest alloc] init] autorelease];  

[requestsetURL:[NSURL URLWithString:urlstr]];  

[requestsetHTTPMethod:@"POST"];  

[requestsetValue:postLengthforHTTPHeaderField:@"Content-Length"];  

[requestsetValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];  

[requestsetHTTPBody:postData];  

 

NSURLConnection*conn=[[NSURLConnection alloc] initWithRequest:requestdelegate:self];  

if(conn)     {  

NSLog(@"Connectionsuccess");

[UIApplicationsharedApplication].networkActivityIndicatorVisible = YES;

[connretain];

}    

else    {  

//inform the user that the download could not be made  

}  

}

// 收到响应时, 会触发

-(void)connection:(NSURLConnection *)connection  didReceiveResponse:(NSURLResponse*)response  {

// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去

NSHTTPURLResponse*httpResponse = (NSHTTPURLResponse*)response;

if([response respondsToSelector:@selector(allHeaderFields)]) {

NSDictionary*dictionary = [httpResponse allHeaderFields];

NSLog([dictionarydescription]);

NSLog(@"%d",[responsestatusCode]);

}

}

//Forward errors to the delegate.

//链接错误   

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error {

//[selfperformSelectorOnMainThread:@selector(httpConnectEnd) withObject:nilwaitUntilDone:NO];

NSLog(@"%@",[errorlocalizedDescription]);

}

//Called when a chunk of data has been downloaded.

//接收数据 每收到一次数据, 会调用一次

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

//Process the downloaded chunk of data.

NSLog(@"%d",[data length]);

//NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

//[selfperformSelectorOnMainThread:@selector(updateProgress) withObject:nilwaitUntilDone:NO];

}

//接收结束

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"%@",connection);

//NSLog(@"%lld",received_);

//[selfperformSelectorOnMainThread:@selector(httpConnectEnd) withObject:nilwaitUntilDone:NO];

// Setthe condition which ends the run loop.

}

iphone:使用NSURLConnection下载网络图片

这是一个很基本的demo,直接看代码,你应该可以看得懂。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

IconDownloader.h

===============================

@interface IconDownloader : NSObject{

NSString *imageURLString;

NSMutableData *activeDownload;

NSURLConnection *imageConnection;

}

@property (nonatomic, retain) NSString *imageURLString;

@property (nonatomic, retain) NSMutableData *activeDownload;

@property (nonatomic, retain) NSURLConnection *imageConnection;

- (void)startDownload;

- (void)cancelDownload;

@end

IconDownloader.m

=====================================

#import "IconDownloader.h"

@implementation IconDownloader

@synthesize activeDownload;

@synthesize imageConnection;

#pragma mark

- (void)dealloc{

[activeDownload release];

[imageConnection cancel];

[imageConnection release];

[super dealloc];

}

- (void)startDownload{

self.activeDownload = [NSMutableData data];

// alloc+init and start an NSURLConnection; release on completion/failure

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:

[NSURLRequest requestWithURL:

[NSURL URLWithString:imageURLString]] delegate:self];

self.imageConnection = conn;

[conn release];

}

- (void)cancelDownload{

[self.imageConnection cancel];

self.imageConnection = nil;

self.activeDownload = nil;

}

#pragma mark -

#pragma mark Download support (NSURLConnectionDelegate)

//每次成功请求到数据后将调下此方法

-       (void)connection:(NSURLConnection *)connection

didReceiveData:(NSData *)data{

//把每次得到的数据依次放到数组中,这里还可以自己做一些

进度条相关的效果

[self.activeDownload appendData:data];

}

-       (void)connection:(NSURLConnection *)connection didFailWith

Error:(NSError *)error{

// Clear the activeDownload property to allow later attempts

self.activeDownload = nil;

// Release the connection now that it's finished

self.imageConnection = nil;

}

-       (void)connectionDidFinishLoading:(NSURLConnection *)

connection{

// Set appIcon and clear temporary data/image

UIImage *image = [[UIImage alloc] initWithData:self.active

Download];

self.activeDownload = nil;

[image release];

// Release the connection now that it's finished

self.imageConnection = nil;

}

@end

NSURLConnection下载文件时,如何显示进度

这里以下载图片举例。

1,首先创建一个cconnection

downloadImage是一个线程函数,在子线程中下载图片。

//url 图片的url地址

- (void)downloadImage:(NSString*)url{

self.uploadPool= [[NSAutoreleasePool alloc] init];

self.characterBuffer = [NSMutableData data];

done = NO;

[[NSURLCache sharedURLCache] removeAllCachedResponses];

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURLURLWithString:url]];

self.connection = [[NSURLConnection alloc] initWithRequest:theRequestdelegate:self];

[self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nilwaitUntilDone:NO];

if (connection != nil) {

do {

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDatedistantFuture]];

} while (!done);

}

self.photo = [UIImage imageWithData:characterBuffer];

[self performSelectorOnMainThread:@selector(fillPhoto) withObject:nilwaitUntilDone:NO];

// Releaseresources used only in this thread.

self.connection = nil;

[uploadPool release];

self.uploadPool = nil;

}

2, 在NSURLConnection的delegate中接收数据

// Forward errors tothe delegate.

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error {

done = YES;

[self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nilwaitUntilDone:NO];

//NSLog(@"%@",[errorlocalizedDescription]);

[characterBuffer setLength:0];

}

// Called when achunk of data has been downloaded.

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

// Process the downloaded chunk of data.

//NSLog(@"%d", [data length]);

received_ += [data length];

[self performSelectorOnMainThread:@selector(updateProgress) withObject:nilwaitUntilDone:NO];

[characterBuffer appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

//NSLog(@"%lld", received_);

[selfperformSelectorOnMainThread:@selector(httpConnectEnd) withObject:nilwaitUntilDone:NO];

// Set the condition which ends the run loop.

done = YES;

}

上面三个方法,第一个是连接出错的情况,第二个是接收数据,reveived_纪录一共接收了多少子节的数据。第三个是连接结束。

还有一个方法,我们可以从http返回的response中拿到一些连接的信息。这里我拿到了要下载的数据的大小,保存在"Content-Length"的字段中,详细的理论见HTTP协议。

-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response{

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

if(httpResponse && [httpResponserespondsToSelector:@selector(allHeaderFields)]){

NSDictionary *httpResponseHeaderFields = [httpResponseallHeaderFields];

total_ = [[httpResponseHeaderFieldsobjectForKey:@"Content-Length"] longLongValue];

//NSLog(@"%lld",total_);

}

}

有了要下载的数据的总大小,和已经下载的大小,进度自然就出来了。

HTTP头协议(重要基础知识)

 HTTP,它用于传送WWW方式的数据。HTTP协议采用了请求/响应模型。客户端向服务器发送一个请求,请求头包含请求的方法、URI、协议版本、以及包含请求修饰符、客户信息和内容的类似于MIME的消息结构。HTTP的头域包括通用头,请求头,响应头和实体头四个部分。每个头域由一个域名,冒号(:)和域值三部分组成。域名是大小写无关的,域值前可以添加任何数量的空格符,头域可以被扩展为多行,在每行开始处,使用至少一个空格或制表符。

libxml中的SAX解析器

用过SAX解析器的朋友都知道,SAX就是事先登录一些处理函数,当XML解析到属性或要素的时候,回调登录的处理函数。

XML的DOM常用2种解析方式:树状解析和节点查找解析。(非常重要基础语法知识)

SAX需要一边读取文件一边解析,速度较快;而DOM采用树状结构保存解析文件。

XMLDOM (文档对象模型)对象提供了一个标准的方法来操作存储在XML文档中的信息,这就是DOM应用编程接口(API)函数。它是应用程序和XML文档之间的桥梁。DOM包含两个关键的抽象概念:一个是树状的层次结构,另一个是用来表示文档内容和结构的节点集合。树状层次包括了所有节点,节点本身也可以包含其他的节点。这样的好处是可以通过这个层次结构来找到并修改某一特定节点的信息。

解析器读取一个XML文档,然后把它的内容解析到一个抽象的信息容器中,该信息容器被称为节点(NODES)。

对象通过暴露的属性和方法来允许浏览、查询和修改XML文档的内容和结构。

设置解析标志

在解析过程中,我们需要得到和设置解析标志。利用不同的解析标志,我们可以用不同的方法来解析一个XML文档。XML标准允许解析器验证或者不验证文档,允许不验证文档的解析过程跳过对外部资源的提取,还可以设置标志来表明是否要从文档中移去多余的空格。(非常重要基础语法知识)

XML文件结构和基本语法

一个XML文件通常包含文件头和文件体两大部分

1. 文件头

XML文件头由XML声明与DTD文件类型声明组成。其中DTD文件类型声明是可以缺少的,关于DTD声明将在后续的内容中介绍,而XML声明是必须要有的,以使文件符合XML的标准规格。

注意:XML声明必须出现在文档的第一行。

2. 文件体

文件体中包含的是XML文件的内容,XML元素是XML文件内容的基本单元。从语法讲,一个元素包含一个起始标记、一个结束标记以及标记之间的数据内容。

XML元素与HTML元素的格式基本相同,其格式如下:

<标记名称 属性名1="属性值1" 属性名1="属性值1" ……>内容</标记名称>

所有的数据内容都必须在某个标记的开始和结束标记内,而每个标记又必须包含在另一个标记的开始与结束标记内,形成嵌套式的分布,只有最外层的标记不必被其他的标记所包含。最外层的是根元素(Root),又称文件(Document)元素,所有的元素都包含在根元素内。

在前面的Flowers.xml文件中,根元素就是<Flowers>,根元素必须而且只能有一个,在该文件有三个<Flower>子元素,这样的元素可以有多个。

  XML的基本语法

1.         注释

XML的注释与HTML的注释相同,以“<!--”开始,以“-->”结束。

2.         区分大小写

在HTML中是不区分大小写的,而XML区分大小写,包括标记,属性,指令等。

3.         标记

XML标记与HTML标记相同,“<”表示一个标记的开始,“>” 表示一个标记的结束。XML中只要有起始标记,就必须有结束标记,而且在使用嵌套结构时,标记之间不能交叉。

在XML中不含任何内容的标记叫做空标记,格式为:<标记名称/>

4.         属性

XML属性的使用与HTML属性基本相同,但需要注意的是属性值要加双引号。

5.         实体引用

实体引用是指分析文档时会被字符数据取代的元素,实体引用用于XML文档中的特殊字符,否则这些字符会被解释为元素的组成部分。例如,如果要显示“<”,需要使用实体引用“<”否则会被解释为一个标记的起始。

XML文件结构

XML文件的结构性内容,包括节点关系以及属性内容等等。

元素是组成XML的最基本的单位,它由开始标记,属性和结束标记组成。

就是一个元素的例子,每个元素必须有一个元素名,元素可以若干个属性以及属性值。

 xml文件和html文件一样,实际上是一个文本文件。显然大家立刻就会明白,创建xml文件最普通的工具和html一样,就是“记事本”了。

一个xml文件的例子

  现在我们暂且使用“记事本”来创建我们的xml文件吧。先看一个xml文件:

  例1

  〈?xmlversion="1.0" encoding="gb2312" ?〉

  〈参考资料〉

   〈书籍〉

        〈名称〉xml入门精解〈/名称〉

        〈作者〉张三〈/作者〉

        〈价格 货币单位="人民币"〉20.00〈/价格〉

   〈/书籍〉

   〈书籍〉

        〈名称〉xml语法〈/名称〉

        〈!--此书即将出版--〉

        〈作者〉李四〈/作者〉

        〈价格 货币单位="人民币"〉18.00〈/价格〉

   〈/书籍〉

  〈/参考资料〉

  这是一个典型的xml文件,编辑好后保存为一个以.xml为后缀的文件。我们可以将此文件分为文件序言(prolog)和文件主体两个大的部分。在此文件中的第一行即是文件序言。该行是一个xml文件必须要声明的东西,而且也必须位于xml文件的第一行,它主要是告诉xml解析器如何工作。其中,version是标明此xml文件所用的标准的版本号,必须要有;encoding指明了此xml文件中所使用的字符类型,可以省略,在你省略此声明的时候,后面的字符码必须是unicode字符码(建议不要省略)。

 文件的其余部分都是属于文件主体,xml文件的内容信息存放在此。我们可以看到,文件主体是由开始的〈参考资料〉和结束的〈/参考资料〉控制标记组成,这个称为xml文件的“根元素”;〈书籍〉是作为直属于根元素下的“子元素”;在〈书籍〉下又有〈名称〉、〈作者〉、〈价格〉这些子元素。货币单位是〈价格〉元素中的一个“属性”,“人民币”则是“属性值”。元素与属性的关系如图1。

  〈!--此书即将出版--〉这一句同html一样,是注释,在xml文件里,注释部分是放在“〈!--”与“--〉”标记之间的部分。

  大家可以看到,xml文件是相当简单的。同html一样,xml文件也是由一系列的标记组成,不过,xml文件中的标记是我们自定义的标记,具有明确的含义,我们可以对标记中的内容的含义作出说明。

xml文件的语法

  对xml文件有了初步的印象之后,我们就来详细地谈一谈xml文件的语法。在讲语法之前,我们必须要了解一个重要的概念,就是xml解析器(xml parse)。

1. xml解析器

  解析器的主要功能就是检查xml文件是否有结构上的错误,剥离xml文件中的标记,读出正确的内容,以交给下一步的应用程序处理。xml是一种用来结构化文件信息的标记语言,xml规范中对于如何标记文件的结构性有一个详细的法则,解析器就是根据这些法则写出来的软件(多用java写成)。

2. well-formed的xml文件

  我们知道,xml必须是well-formed的,才能够被解析器正确地解析出来,显示在浏览器中。那么什么是well-formed的xml文件呢?主要有下面几个准则,我们在创建xml文件的时候,必须满足它们。

  首先,xml文件的第一行必须是声明该文件是xml文件以及它所使用的xml规范版本。在文件的前面不能够有其它元素或者注释。

  第二,在xml文件中有且只能够有一个根元素。我们的第一个例子中,〈参考资料〉... 〈/参考资料〉就是此xml文件的根元素。

xml文件中,用的大多都是自定义的标记。

  第三,在xml文件中的标记必须正确地关闭,也就是说,在xml文件中,控制标记必 须有与之对应的结束标记。如:〈名称〉标记必须有对应的〈/名称〉结束标记,不像html,某些标记的结束标记可有可无。如果在xml文件中遇到自成一个单元的标记,就是类似于html 中的〈imgsrc=.....〉的这些没有结束标记的时候,xml把它称为“空元素”,必须用这样的写法:〈空元素名/〉,如果元素中含有属性时写法则为:〈空元素名 属性名=“属性值”/〉。

  第四,标记之间不得交叉。在以前的html文件中,可以这样写:

  〈b〉〈h〉xxxxxxx〈/b〉〈/h〉,〈b〉和〈h〉

  标记之间有相互重叠的区域,而在xml中,是严格禁止这样标记交错的写法,标记必须以规则性的次序来出现。

  第五,属性值必须要用“ ”号括起来。如第一个例子中的“1.0”、“gb2312”、“人民币”。都是用“ ”号括起来了的,不能漏掉。

  第六,控制标记、指令和属性名称等英文要区分大小写。与html不同的是,在html中, 类似〈b〉和〈b〉的标记含义是一样的,而在xml中,类似〈name〉、〈name〉或〈name〉这样的标记是不同的。

  第七,我们知道,在html文件中,如果我们要浏览器原封不动地将我们所输入的东西显示出来,可以将这些东西放到〈pre〉〈/pre〉或者〈xmp〉〈/xmp〉标记中间。这对于我们创建html教学的网页是必不可少的,因为网页中要显示html的源代码。而在xml中,要实现这样的功能,就必须使用cdata标记。在cdata标记中的信息被解析器原封不动地传给应用程序,并且不解析该段信息中的任何控制标记。cdata区域是由:“〈![cdata[”为开始标记,以“]]〉”为结束标记。例如:例2中的源码,除了“〈![cdata[”和“]]〉”符号,其余的内容解析器将原封不动地交给下游的应用程序,即使cdata区域中的开始和结尾的空白以及换行字符等,都同样会被转交(注意cdata是大写的字符)。

要进行XML的DOM解析必须搞清以下几个知识点:XML文件结构、树状解析、节点解析、HTTP头协议。

iPhone开源项目汇总(更新版)

扫描wifi信息:

http://code.google.com/p/uwecaugmentedrealityproject/

http://code.google.com/p/iphone-wireless/

条形码扫描:

http://zbar.sourceforge.net/iphone/sdkdoc/install.html

tcp/ip的通讯协议:

http://code.google.com/p/cocoaasyncsocket/

voip/sip:

http://code.google.com/p/siphon/

http://code.google.com/p/asterisk-voicemail-for-iphone/

http://code.google.com/p/voiphone/

three20

https://github.com/facebook/three20

google gdata

http://code.google.com/p/gdata-objectivec-client/

720全景显示panoramagl

http://code.google.com/p/panoramagl/

jabber client

http://code.google.com/p/ichabber/

PLBlocks

http://code.google.com/p/plblocks/

image processing

http://code.google.com/p/simple-iphone-image-processing/

json编码解码:http://code.google.com/p/json-framework

base64编码解码:http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/?r=87

xml解析:https://github.com/schwa/TouchXML

安全保存用户密码到keychain中:https://github.com/ldandersen/scifihifi-iphone

加载等待特效框架(privateapi):https://github.com/jdg/MBProgressHUD

http等相关协议封装:http://allseeing-i.com/ASIHTTPRequest

下拉刷新代码:https://github.com/enormego/EGOTableViewPullRefresh

异步加载图片并缓存代码:http://www.markj.net/iphone-asynchronous-table-image/

iphone TTS:https://bitbucket.org/sfoster/iphone-tts

iphone cook book 源码:https://github.com/erica/iphone-3.0-cookbook-

iphone正则表达式:http://regexkit.sourceforge.net/RegexKitLite/

OAuth认证:  http://code.google.com/p/oauth/

http://code.google.com/p/oauthconsumer/

蓝牙协议栈:http://code.google.com/p/btstack/

语音识别:http://www.politepix.com/openears/

ShareKit:http://www.getsharekit.com/install/

日历控件:http://code.google.com/p/iphonecal/

https://github.com/klazuka/Kal

zlib, openssl:http://code.google.com/p/ios-static-libraries/

地球显示信息:http://code.google.com/p/whirlyglobe/

原帖地址:http://www.cocoachina.com/bbs/read.php?tid=47282

原文地址:http://blog.csdn.net/favormm/article/details/6105793

图像及动画处理五:进度条

-(id)initWithFrame:(CGRect)aFrameframeColor:(UIColor*)aFrameColor barColor:(UIColor*)aBarColor;

arguments-

aFrame:边框

aFrameColor:边框颜色

aBarColor:进度条颜色

return value-UIView格式

-(void)setProgress:(float)progress;

progress:范围为[0,1]

其它细节,可在方法体内自行修改,显示效果如下图:WProgressBar

美化UILabel中的字体 UILabdel.zip

图像及动画处理六:选取器(dataPicker仿苹果)

本文实现了苹果的选取器,与苹果自带的选取器相比有以下特点:

单行,横向放置,大小可配置,内容可配置且方法简单,同时可容纳文字和图片

(1) tasks:

-(id)initWithFrame:(CGRect)framearray:(NSArray*)list row:(int)aRow;

-(int)index;

(2)discussions:

1)-(id)initWithFrame:(CGRect)framearray:(NSArray*)list row:(int)aRow;

arguments:

frame: the frame ofthe component view

list: the contentlisted on the component view, in format of NSString and UIImage only

row: the number ofrow displaying on the component, limited to be 1,3,5 and 7 only

return value: asubclass of UIView

2)-(int)index;

return value: to indicatewhich section is chosen.

(3)attentions:

the background imageis in the format "png", so it may looks ugly when scaling it

or setting its framesome times. when that happens, it is suggested to rescale it or

change the image inthe file "bg.png"

效果如图:

http://www.cocoachina.com/iphonedev/sdk/2011/1110/3483.html

[url=job.php?action=download&aid=26420][/url]

iOS运行回路(RunLoop)总结

http://www.cocoachina.com/iphonedev/sdk/2011/1111/3487.html

创建iPhone锁定划动条的方法

iPhone关闭屏幕后可以自动锁定。下面的代码可以创建一个这样的划动条。

代码如下:

7.#import <telephonyui /TelephonyUI.h>

8.

9.TPBottomLockBar* lockBar = [ [ TPBottomLockBar alloc ]initWithFrame:CGRectMake(0.0f, 340.0f, 320.0f, 100.0f) knobColor:1];

10.

11.        [lockBarsetLabel:@"Slide To Unlock"];

12.        [lockBarsetFontSize: 14];

13.        [lockBarsetDelegate: self];

14.        [contentViewaddSubview: lockBar];

15.        [lockBarstartAnimating];

16.

17.        </telephonyui>

创建之后如果要获取解锁,可以重载unlock方法

8.- (void)unlock

9.{

10.

11.        //dosomething

12.

}

iPhone开发之自定义UIActionSheet

利用UITableView实现对图片的展示

前一段时间在[url=?u=3584]CocoaChina[/url]上看到过关于如何在Iphone中显示图片,今天就试试,顺便复习了一下UITableView了。先上两张图片了。

其实也是比较简单的了,首先在NSArray中加入要显示的图片的名称,方便后面的读取,然后就是再创建一个空的view用来显示需要展示的图片,在就是要创建一个UINavigationController,下面来看看具体怎么操作。

首先创建一个viewBased的空项目。添加一个新的xib文件和一个新类。名字自己取,然后关联你刚才的类和xib文件,实现controller控制model。

在创建的新类中定义一个UIImageView,用来显示展示的图片。还需要定义一个方法用来接收传过来的图片的名称。这样新的类基本上就创建好了。

打开MainWindow.xib文件,向里面拖入一个NavigationController,在项目的delegate里面声明一个UINavigationController,并且在window中加入该view。[windowaddSubview:NavigationController.view],然后就是修改ViewController类了。引入你创建的新类,声明一个用来保存图片名称的NSArray对象,和一个UITableView对象。在viewDidLoad中填充NSArray对象,初始化UITableView,设置Delegates和DataSource。

-(void)viewDidLoad{

array =[[NSArrayalloc]initWithObjects:@"p1.png",@"p2.png",@"p3.png",@"p4.png",@"p5.png",nil];

self.title =@"Pictures";

table =[[UITableView alloc]initWithFrame:CGRectMake(0,0,320,420)];

[tablesetDelegate:self];

[tablesetDataSource:self];

[self.viewaddSubview:table];

[tablerelease];

[superviewDidLoad];

[tablesetSeparatorColor:[UIColorgreenColor]];//修改tableviewcell的线的颜色

}

下面就是用UITableView的3部曲了:

-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{

return 1;

}

-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger) section{

return [arraycount];

}

-(UITableViewCell*)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)path{

staticNSString *s = @"s";

UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:s];

if(cell ==nil){

cell =[[[UITableViewCellalloc]initWithFrame:CGRectZeroreuseIdentifier:s]autorelease];

UILabel*DataLabel = [[UILabelalloc] initWithFrame:CGRectMake(80, 0, 320, 44)];

[DataLabelsetTag:100];

DataLabel.autoresizingMask=UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;

[cell.contentViewaddSubview:DataLabel];

[DataLabelrelease];

}

UILabel*DataLabel = (UILabel *)[cell.contentViewviewWithTag:100];

[DataLabelsetFont:[UIFontboldSystemFontOfSize:18]];

cell.image =[UIImage imageNamed:[NSStringstringWithFormat:@"p%d.png", path.row+1]];

DataLabel.text= [arrayobjectAtIndex:path.row];

cell.accessoryType= UITableViewCellAccessoryDisclosureIndicator;

returncell;

}

下面是实现点击TableView中的行的时候实现导航,导航到图片信息页。

-(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if(picShow ==nil){

picShow= [[show alloc]initWithNibName:@"Pictures" bundle:nil];

}

[self.navigationControllerpushViewController:picShowanimated:YES];

[picShowshowPictures:[arrayobjectAtIndex:[indexPath row]]];

}

最后释放掉资源。这个是我自己为了温习,学习用的。例子程序可以去我的CSDN上面下载。http://hanyegudeng.download.csdn.net/

[ 此帖被haoxue在2011-11-1514:16重新编辑 ]

图片:60b45f23g753f9dce29b0&690.png

图片:60b45f23g753f9e298277&690.jpg

iOS5新特性:强大的CoreImage

iOS5给我们带来了很多很好很强大的功能和API。CoreImage就是其中之一,它使我们很容易就能处理图片的各种效果,色彩啊,曝光啊,饱和度啊,变形啊神马的。

可惜苹果一直没能完善官方文档,也没有推出示例代码,所以国内很多同学可能还没有开始使用。

但国外的大神们已经证明这是个相当强悍的框架,不仅功能强大,而且可以直接使用GPU,效率奇高,甚至可以实时的对视频进行渲染。

下面让我们来看看,如何具体使用它:

首先你需要导入CoreImage.framework 框架;进行Mac(不是iOS)开发的同学请导入QuartzCore.framework 框架,包含在其中了。

然后我们先来看看3个主要的类:

CIContext:它与Core Graphics 和 OpenGL context类似,所有Core Image的处理流程都通过它来进行;

CIImage:它用来存放图片数据,可以通过UIImage,图片文件或像素数据创建;

CIFilter:通过它来定义过滤器的详细属性。

CIContext有两种初始化方法,分别对应GPU和CPU

// 创建基于GPU的CIContext对象

context = [CIContextcontextWithOptions: nil];

// 创建基于CPU的CIContext对象

//context =[CIContext contextWithOptions: [NSDictionary dictionaryWithObject:[NSNumbernumberWithBool:YES]

forKey:kCIContextUseSoftwareRenderer]];

一般采用第一种基于GPU的,因为效率要比CPU高很多,但是要注意的是基于GPU的CIContext对象无法跨应用访问。

比如你打开UIImagePickerController要选张照片进行美化,如果你直接在UIImagePickerControllerDelegate的委托方法里调用CIContext对象进行处理,那么系统会自动将其降为基于CPU的,速度会变慢,所以正确的方法应该是在委托方法里先把照片保存下来,回到主类里再来处理。(代码里你将会看到)

CIImage的初始化方法有很多,常用的也是2种:

// 通过图片路径创建CIImage

NSString *filePath =[[NSBundle mainBundle] pathForResource:@"image"ofType:@"png"];

NSURL*fileNameAndPath = [NSURL fileURLWithPath:filePath];

beginImage = [CIImageimageWithContentsOfURL:fileNameAndPath];

// 通过UIImage对象创建CIImage

UIImage *gotImage =...;

beginImage =[CIImage imageWithCGImage:gotImage.CGImage];

CIFilter初始化:

// 创建过滤器

filter = [CIFilterfilterWithName:@"CISepiaTone"];

[filtersetValue:beginImage forKey:kCIInputImageKey];

[filtersetValue:[NSNumber numberWithFloat:slideValue]forKey:@"inputIntensity"];

第一行:指定使用哪一个过滤器,通过[CIFilter filterNamesInCategory: kCICategoryBuiltIn]能得到所有过滤器的列表

第二行:指定需要处理的图片

第三行:指定过滤参数,每个过滤器的参数都不一样,可以在官方文档里搜索“Core Image Filter Reference”查看

得到过滤后的图片并输出:

CIImage *outputImage= [filter outputImage];

CGImageRef cgimg =[context createCGImage:outputImage fromRect:[outputImage extent]];

UIImage *newImg =[UIImage imageWithCGImage:cgimg];

[imgVsetImage:newImg];

CGImageRelease(cgimg);

第一行:通过[filteroutputImage]可以得到过滤器输出的图片

第二行:通过CIContext的方法createCGImage: fromRect:得到CGImage

第三行:转化为UIImage,这样我们就可以跟据需要显示在界面上了

至此一个过滤周期就完成了,简单来说分以下几个步骤:

1 初始化CIContext,CIImage

2 初始化CIFilter并设置参数

3 得到输出的图片

4 将图片转化成能显示的UIImage类型

如果想一张图片有多种过滤效果就需要重复2,3两步,并且要将上一个过滤器输出的图片作为下一个过滤器的参数

简单吧!几行代码就可以得到丰富的效果哦,我在代码里实现了3种效果。

[url=../cms/uploads/soft/111115/CoreImage.zip]CoreImage[/url]

目前为止最为接近iBook的翻页效果

Book的翻页效果一直是大家追求的特效,可惜ios5前,苹果都没有开放出来。在ios5中,苹果开放了PageViewController,于是这种效果得到了官方支持。

今天要给大家介绍的源码是ES实现的翻页效果,是目前为止最接近iBook的效果了, 是实时的哟。目前源码是alpha版,开发人员还在继续完善,相信将来可能超越iBook哟,大家敬请关注。

介绍:http://api.mutado.com/mobile/paperstack/

源码:https://github.com/lomanf/PaperStack

推荐几个经典iOS开源类库及工具

几个常用的开源类库及下载地址:

1.json json编码解码

2.GTMBase64 base64编码解码

3.TouchXML xml解析

4.SFHFKeychainUtils 安全保存用户密码到keychain中

5.MBProgressHUD 很棒的一个加载等待特效框架

6.ASIHTTPRequest http等相关协议封装

7.EGORefreshTableHeaderView 下拉刷新代码

8.AsyncImageView 异步加载图片并缓存代码

9.类似setting的竖立也分栏程序

UIScrollView的setContentOffset方法

在UIScrollView中,setContentOffset方法的功能是跳转到你指定内容的坐标,

[self.scroview setContentOffset:CGPointMake(0,50)animated:YES];

这样就行了`

但是,今天突然发现了一个问题:

当设置了scroview.pagingEnabled= YES;的时候

在你执行setContentOffset方法过后,再执行其他操作时,指定内容的坐标将被还原,pagingEnabled属性会对它进行重置。

循环滚动UIScrollView(无点击事件处理)

1.创建一个继承UIView的名为CycleScrollView的类(.h和.m文件)

2.将下面代码替换原默认代码

3.在你的类里面实例化一个CycleScrollView类的对象并用

-(id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)directionpictures: (NSArray*)pictureArray

进行初始化

参数介绍:

frame 页面的位置和大小

direction滚动的方向,0垂直滚动,1水平滚动

pictures滚动的图片数组

比如:

-(void)viewDidLoad{

[superviewDidLoad];

NSArray*imagesArray=[[NSArray alloc] initWithObjects:[UIImage         imageNamed:@"test1.jpg"],[UIImageimageNamed:@"test2.jpg"],[UIImageimageNamed:@"test3.jpg"],nil];

CycleScrollView *cycle=[[CycleScrollView alloc]initWithFrame:CGRectMake(0, 0,320, 480)     cycleDirection:0pictures:imagesArray];

cycle.delegate=self;

[self.viewaddSubview:cycle];

[imagesArrayrelease];

[cyclerelease];

}/

.h文件

#import<UIKit/UIKit.h>

typedef  enum_CycleDirection

{PortaitDirection,LandscapeDirection } CycleDirection;

@interfaceCycleScrollView :UIView<UIScrollViewDelegate> {

UIScrollView*scrollView;

UIImageView*curImageView;

inttotalPage;

intcurPage;

CGRectscrollFrame;

CycleDirectionscrollDirection;  // scrollView滚动的方向

NSArray*imagesArray;  //存放所有需要滚动的图片

NSMutableArray *curImages; //存放当前滚动的三张图片

}

- (int)validPageValue:(NSInteger)value;

- (id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)directionpictures:(NSArray*)pictureArray;

- (NSArray*)getDisplayImagesWithCurpage:(int)page;

- (void)refreshScrollView;

@end

/

/

.m文件

#import"CycleScrollView.h"

@implementationCycleScrollView

- (id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)directionpictures:(NSArray*)pictureArray{

self=[superinitWithFrame:frame];

if(self) {

scrollFrame=frame;

scrollDirection=direction;

totalPage=[pictureArray count];

curPage=1;  //当前显示的是图片数组里的第一张图片

curImages=[[NSMutableArray alloc] init];

imagesArray=[[NSArray alloc] initWithArray:pictureArray];

scrollView=[[UIScrollView alloc] initWithFrame:frame];

scrollView.backgroundColor=[UIColor blueColor];

scrollView.showsHorizontalScrollIndicator=NO;

scrollView.showsVerticalScrollIndicator=NO;

scrollView.pagingEnabled=YES;

scrollView.delegate=self;

[selfaddSubview:scrollView];

if(scrollDirection==PortaitDirection)  //在竖直方向滚动{

scrollView.contentSize=CGSizeMake(scrollView.frame.size.width,scrollView.frame.size.height*3); //竖直方法可以存放三张图片

}

if(scrollDirection==LandscapeDirection) //在水平方向滚动{

scrollView.contentSize=CGSizeMake(scrollView.frame.size.width*3,scrollView.frame.size.height);

}

[selfaddSubview:scrollView];

[selfrefreshScrollView];

}

returnself;

}

- (void)refreshScrollView{

NSArray*subViews=[scrollView subviews];

if([subViewscount]!=0){

[subViewsmakeObjectsPerformSelector:@selector(removeFromSuperview)];

}

[selfgetDisplayImagesWithCurpage:curPage];

UIImage*preImage=[curImagesobjectAtIndex:0];

UIImage*curImage=[curImages objectAtIndex:1];

UIImage*lastImage=[curImages objectAtIndex:2];

UIImageView*preView=[[UIImageView alloc] initWithImage:preImage];

UIImageView*curView=[[UIImageView alloc] initWithImage:curImage];

UIImageView*lastView=[[UIImageView alloc] initWithImage:lastImage];

[scrollViewaddSubview:preView];

[scrollViewaddSubview:curView];

[scrollViewaddSubview:lastView];

[preView release];

[curView release];

[lastView release];

if(scrollDirection==PortaitDirection)  //竖直滚动{

preView.frame=CGRectOffset(preView.frame, 0, 0);

curView.frame=CGRectOffset(curView.frame,0,scrollFrame.size.height);

lastView.frame=CGRectOffset(lastView.frame, 0,2*scrollFrame.size.height);

[scrollViewsetContentOffset:CGPointMake(0,scrollFrame.size.height)];

}

if(scrollDirection==LandscapeDirection) //水平滚动 {

preView.frame=CGRectOffset(preView.frame, 0, 0);

curView.frame=CGRectOffset(curView.frame, scrollFrame.size.width,0);

lastView.frame=CGRectOffset(lastView.frame,scrollFrame.size.width*2, 0);

[scrollView setContentOffset:CGPointMake(scrollFrame.size.width,0)];

}

}

- (NSArray*)getDisplayImagesWithCurpage:(int)page  {

intpre=[selfvalidPageValue:curPage-1];

intlast=[selfvalidPageValue:curPage+1];

if([curImagescount]!=0)  [curImages removeAllObjects];

[curImagesaddObject:[imagesArrayobjectAtIndex:pre-1]];

[curImagesaddObject:[imagesArray objectAtIndex:curPage-1]];

[curImagesaddObject:[imagesArray objectAtIndex:last-1]];

returncurImages;

}

-(int)validPageValue:(NSInteger)value  {

if(value==0)  value=totalPage;  //value=1为第一张,value=0为前面一张

if(value==totalPage+1)

value=1;

returnvalue;

}

- (void)scrollViewDidScroll:(UIScrollView *)crollView {

intx=crollView.contentOffset.x;

inty=crollView.contentOffset.y;

if(scrollDirection==LandscapeDirection) //水平滚动 {

if(x>=2*scrollFrame.size.width) //往下翻一张 {

curPage=[selfvalidPageValue:curPage+1];

[selfrefreshScrollView];

}

if(x<=0)  {

curPage=[selfvalidPageValue:curPage-1];

[self refreshScrollView];

}

}

//竖直滚动

if(scrollDirection==PortaitDirection)  {

if(y>=2*scrollFrame.size.height){

curPage=[selfvalidPageValue:curPage+1];

[selfrefreshScrollView];

}

if (y<=0){

curPage=[self validPageValue:curPage-1];

[selfrefreshScrollView];

}

}

}

- (void)dealloc  {

[imagesArray release];

[curImages release];

[super dealloc];

}

@end

怎样让程序第一次加载的时候默认选中TableView的第一行?

使tableview在界面启动后定位在x行

在viewDidLoad中加入以下代码

NSIndexPath *idxPath= [NSIndexPath indexPathForRow:x inSection:0];

[self.tableView scrollToRowAtIndexPath:idxPath

atScrollPosition:UITableViewScrollPositionMiddle

animated:NO];

你先试试,有好多方法的!

首先选择行数你会的吧?selectRowAtIndexes:

滚动的话tableview的superview时scrollview,scrollview可以滚动到某个position

那么就要计算这个position

position = table row height * index

项目过程中各种具体方法的实现!

1、设置View的backgroundcolor像TableiewGrouped那种风格:

[UIColorgroupTableViewBackgroundColor]

2、关于tableview的移动距离,可以用下面的delegate实现

-(void)scrollViewDidScroll:(UIScrollView *)sender

具体的移动长度可以利用contentOffset求得

3、使得tableview在界面启动后定位在某一行

在viewDidLoad中加入以下代码

NSIndexPath *idxPath = [NSIndexPath indexPathForRow:5 inSection:0];

[self.tableView scrollToRowAtIndexPath:idxPath

atScrollPosition:UITableViewScrollPositionMiddle

animated:NO];

4、如果希望iPhone App里包含让tableView滚到顶部的功能,注意UITabelView 继承自UIScrollView,而setContentOffset是scrollview里头一个方法。

[pre]-(void)scrollToTop:(BOOL)animated {

[selfsetContentOffset:CGPointMake(0,0) animated:animated];

}

- (void)scrollToBottom:(BOOL)animated{

NSUIntegersectionCount = [self numberOfSections];

if (sectionCount){

NSUIntegerrowCount = [self numberOfRowsInSection:0];

if(rowCount) {

NSUIntegerii[2] = {0, rowCount-1};

NSIndexPath*indexPath = [NSIndexPath indexPathWithIndexes:ii length:2];

[selfscrollToRowAtIndexPath:indexPathatScrollPosition:UITableViewScrollPositionBottom

animated:animated];

}

}

}[ 此帖被haoxue在2012-02-25 22:38重新编辑 ]

iOS5系统API和5个开源库的JSON解析速度测试

iOS5新增了JSON解析的API,我们将其和其他五个开源的JSON解析库进行了解析速度的测试,下面是测试的结果。

我们选择的测试对象包含下面的这几个框架,其中NSJSONSerialization是iOS5系统新增的JSON解析的API,需要iOS5的环境,如果您在更低的版本进行测试,应该屏蔽相应的代码调用。

- [SBJSON(json-framework)](http://code.google.com/p/json-framework/)

- [TouchJSON (fromtouchcode)](http://code.google.com/p/touchcode/)

- [YAJL (objective-Cbindings)](http://github.com/gabriel/yajl-objc)

- [JSONKit](https://github.com/johnezang/JSONKit)

- [NextiveJson](https://github.com/nextive/NextiveJson)

-[NSJSONSerialization](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946)

我们选择了四个包含json格式的数据的文件进行测试。每一个文件进行100的解析动作,对解析的时间进行比较。

工程包含以下的文件和框架:

测试时间间隔的的代码的宏定义如下,其中计算的次数和解析的代码由外部调用传入:

#define RunWithCount(count,description, expr) \

do { \

CFAbsoluteTime start =CFAbsoluteTimeGetCurrent(); \

for(NSInteger i = 0; i < count;i++) { \

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \

expr; \

[pool release]; \

} \

\

CFTimeInterval took =CFAbsoluteTimeGetCurrent() - start; \

NSLog(@"%@ %0.3f",description, took); \

\

} while (0)

这是外面调用的代码,设置读取的json文件和计算的次数,每一个函数在进行对应框架API的解析代码:

JSONTest *test = [[JSONTest alloc] init];

NSInteger count = 100;

[test runWithResourceName:@"twitter_public.json" count:count];

[test runWithResourceName:@"lastfm.json" count:count];

[test runWithResourceName:@"delicious_popular.json" count:count];

[test runWithResourceName:@"yelp.json" count:count];

我们的测试的环境是Xcode 4.2和iOS5,计算次数是100次,这是计算的结果Log:

2011-11-2414:48:59.441 JSONPerfTest[9716:207] SBJSON-twitter_public.json 0.335

2011-11-2414:48:59.625 JSONPerfTest[9716:207] YAJL-twitter_public.json 0.183

2011-11-2414:49:00.095 JSONPerfTest[9716:207] TouchJSON-twitter_public.json 0.469

2011-11-2414:49:00.226 JSONPerfTest[9716:207] JSONKit-twitter_public.json 0.130

2011-11-2414:49:00.390 JSONPerfTest[9716:207] NextiveJson-twitter_public.json 0.164

2011-11-2414:49:00.504 JSONPerfTest[9716:207] NSJSONSerialization-twitter_public.json0.113

2011-11-2414:49:01.196 JSONPerfTest[9716:207] SBJSON-lastfm.json 0.691

2011-11-2414:49:01.516 JSONPerfTest[9716:207] YAJL-lastfm.json 0.320

2011-11-2414:49:02.367 JSONPerfTest[9716:207] TouchJSON-lastfm.json 0.850

2011-11-2414:49:02.580 JSONPerfTest[9716:207] JSONKit-lastfm.json 0.212

2011-11-2414:49:02.861 JSONPerfTest[9716:207] NextiveJson-lastfm.json 0.280

2011-11-2414:49:03.039 JSONPerfTest[9716:207] NSJSONSerialization-lastfm.json 0.177

2011-11-2414:49:03.546 JSONPerfTest[9716:207] SBJSON-delicious_popular.json 0.506

2011-11-2414:49:03.787 JSONPerfTest[9716:207] YAJL-delicious_popular.json 0.240

2011-11-2414:49:04.460 JSONPerfTest[9716:207] TouchJSON-delicious_popular.json 0.672

2011-11-2414:49:04.668 JSONPerfTest[9716:207] JSONKit-delicious_popular.json 0.207

2011-11-2414:49:04.904 JSONPerfTest[9716:207] NextiveJson-delicious_popular.json 0.234

2011-11-2414:49:05.072 JSONPerfTest[9716:207] NSJSONSerialization-delicious_popular.json0.168

2011-11-2414:49:05.434 JSONPerfTest[9716:207] SBJSON-yelp.json 0.361

2011-11-2414:49:05.633 JSONPerfTest[9716:207] YAJL-yelp.json 0.198

2011-11-2414:49:06.154 JSONPerfTest[9716:207] TouchJSON-yelp.json 0.519

2011-11-2414:49:06.310 JSONPerfTest[9716:207] JSONKit-yelp.json 0.155

2011-11-2414:49:06.497 JSONPerfTest[9716:207] NextiveJson-yelp.json 0.186

2011-11-2414:49:06.637 JSONPerfTest[9716:207] NSJSONSerialization-yelp.json 0.140

将上面的数据整理成下面的图表:

测试的结果显示,系统的API的解析速度最快,我们在工程项目中选择使用,也是应用较为广泛的SBJSON的解析速度为倒数第二差,令我大跌眼镜。

与系统API较为接近的应该是JSONKit。

这里没有对API的开放接口和使用方式进行比较,若单纯基于以上解析速度的测试:

1:iOS5应该选择系统的API进行

2:不能使用系统API的应该选择JSONKit

基于第三方AsyncSocket 的tcp/udp Demo分享

内附tcp服务器 和tcp客户端。以及UDP全套

附件:  TestAsyncSocket.zip (534 K) 下载次数:89

获得通讯录中联系人的所有属性

获得通讯录中联系人的所有属性 ,看代码:

ABAddressBookRef addressBook= ABAddressBookCreate();

CFArrayRef results =ABAddressBookCopyArrayOfAllPeople(addressBook);

for(int i = 0; i <CFArrayGetCount(results); i++){

ABRecordRef person =CFArrayGetValueAtIndex(results, i);

//读取firstname

NSString *personName = (NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);

if(personName != nil)

textView.text =[textView.text stringByAppendingFormat:@"\n姓名:%@\n",personName];

//读取lastname

NSString *lastname =(NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

if(lastname != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",lastname];

//读取middlename

NSString *middlename =(NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);

if(middlename != nil)

textView.text = [textView.textstringByAppendingFormat:@"%@\n",middlename];

//读取prefix前缀

NSString *prefix =(NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);

if(prefix != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",prefix];

//读取suffix后缀

NSString *suffix =(NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);

if(suffix != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",suffix];

//读取nickname呢称

NSString *nickname =(NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);

if(nickname != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",nickname];

//读取firstname拼音音标

NSString *firstnamePhonetic= (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);

if(firstnamePhonetic != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic];

//读取lastname拼音音标

NSString *lastnamePhonetic =(NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);

if(lastnamePhonetic != nil)

textView.text = [textView.textstringByAppendingFormat:@"%@\n",lastnamePhonetic];

//读取middlename拼音音标

NSString *middlenamePhonetic= (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);

if(middlenamePhonetic !=nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic];

//读取organization公司

NSString *organization =(NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);

if(organization != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",organization];

//读取jobtitle工作

NSString *jobtitle =(NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);

if(jobtitle != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",jobtitle];

//读取department部门

NSString *department =(NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);

if(department != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",department];

//读取birthday生日

NSDate *birthday =(NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);

if(birthday != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",birthday];

//读取note备忘录

NSString *note =(NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);

if(note != nil)

textView.text =[textView.text stringByAppendingFormat:@"%@\n",note];

//第一次添加该条记录的时间

NSString *firstknow =(NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);

NSLog(@"第一次添加该条记录的时间%@\n",firstknow);

//最后一次修改該条记录的时间

NSString *lastknow =(NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);

NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

//获取email多值

ABMultiValueRef email =ABRecordCopyValue(person, kABPersonEmailProperty);

int emailcount =ABMultiValueGetCount(email);

for (int x = 0; x <emailcount; x++){

//获取email Label

NSString* emailLabel =(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email,x));

//获取email值

NSString* emailContent =(NSString*)ABMultiValueCopyValueAtIndex(email, x);

textView.text =[textView.textstringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];

}

//读取地址多值

ABMultiValueRef address =ABRecordCopyValue(person, kABPersonAddressProperty);

int count =ABMultiValueGetCount(address);

for(int j = 0; j < count;j++){

//获取地址Label

NSString* addressLabel =(NSString*)ABMultiValueCopyLabelAtIndex(address, j);

textView.text =[textView.text stringByAppendingFormat:@"%@\n",addressLabel];

//获取該label下的地址6属性

NSDictionary* personaddress=(NSDictionary*) ABMultiValueCopyValueAtIndex(address,j);

NSString* country =[personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];

if(country != nil)

textView.text =[textView.text stringByAppendingFormat:@"国家:%@\n",country];

NSString* city =[personaddress valueForKey:(NSString *)kABPersonAddressCityKey];

if(city != nil)

textView.text =[textView.text stringByAppendingFormat:@"城市:%@\n",city];

NSString* state =[personaddress valueForKey:(NSString *)kABPersonAddressStateKey];

if(state != nil)

textView.text =[textView.text stringByAppendingFormat:@"省:%@\n",state];

NSString* street =[personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];

if(street != nil)

textView.text =[textView.text stringByAppendingFormat:@"街道:%@\n",street];

NSString* zip =[personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];

if(zip != nil)

textView.text = [textView.textstringByAppendingFormat:@"邮编:%@\n",zip];

NSString* coutntrycode =[personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];

if(coutntrycode != nil)

textView.text =[textView.text stringByAppendingFormat:@"国家编号:%@\n",coutntrycode];

}

//获取dates多值

ABMultiValueRef dates =ABRecordCopyValue(person, kABPersonDateProperty);

int datescount =ABMultiValueGetCount(dates);

for (int y = 0; y <datescount; y++){

//获取dates Label

NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates,y));

//获取dates值

NSString* datesContent =(NSString*)ABMultiValueCopyValueAtIndex(dates, y);

textView.text =[textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];

}

//获取kind值

CFNumberRef recordType =ABRecordCopyValue(person, kABPersonKindProperty);

if (recordType ==kABPersonKindOrganization) {

// it's a company

NSLog(@"it's acompany\n");

} else {

// it's a person, resource,or room

NSLog(@"it's a person, resource,or room\n");

}

//获取IM多值

ABMultiValueRefinstantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);

for (int l = 1; l <ABMultiValueGetCount(instantMessage); l++){

//获取IM Label

NSString*instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage,l);

textView.text =[textView.text stringByAppendingFormat:@"%@\n",instantMessageLabel];

//获取該label下的2属性

NSDictionary*instantMessageContent =(NSDictionary*)ABMultiValueCopyValueAtIndex(instantMessage,l);

NSString* username =[instantMessageContent valueForKey:(NSString*)kABPersonInstantMessageUsernameKey];

if(username != nil)

textView.text =[textView.text stringByAppendingFormat:@"username:%@\n",username];

NSString* service=[instantMessageContent valueForKey:(NSString*)kABPersonInstantMessageServiceKey];

if(service != nil)

textView.text =[textView.text stringByAppendingFormat:@"service:%@\n",service];

}

//读取电话多值

ABMultiValueRef phone=ABRecordCopyValue(person, kABPersonPhoneProperty);

for (int k = 0;k<ABMultiValueGetCount(phone); k++)

{

//获取电话Label

NSString * personPhoneLabel=(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone,k));

//获取該Label下的电话值

NSString * personPhone =(NSString*)ABMultiValueCopyValueAtIndex(phone, k);

textView.text =[textView.textstringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];

}

//获取URL多值

ABMultiValueRef url =ABRecordCopyValue(person, kABPersonURLProperty);

for (int m = 0; m <ABMultiValueGetCount(url); m++){

//获取电话Label

NSString * urlLabel =(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url,m));

//获取該Label下的电话值

NSString * urlContent =(NSString*)ABMultiValueCopyValueAtIndex(url,m);

textView.text =[textView.text stringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];

}

//读取照片

NSData *image =(NSData*)ABPersonCopyImageData(person);

UIImageView *myImage =[[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];

[myImage setImage:[UIImageimageWithData:image]];

myImage.opaque = YES;

[textView addSubview:myImage];

}

CFRelease(results);

CFRelease(addressBook);

iphone 开发入门经典源码,希望对初学者们有帮助!127楼

附件:  51CTO下载-Objective-C基础教程随书源码.zip (1461 K) 下载次数:144

声音源码的demo

附件:  shengyinchuan1.zip (746 K) 下载次数:96

iPhone几种截屏的代码分享

1.      UIGraphicsBeginImageContextWithOptions(pageView.page.bounds.size,YES, zoomScale);

[pageView.page.layerrenderInContext:UIGraphicsGetCurrentContext()];

UIImage*uiImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

2.

- (UIImage *)glToUIImage {

DWScrollView*pageView = [self getActivePageView];

pageView.page.backgroundColor = [UIColor clearColor];

//  self.backgroundColor=[UIColorclearColor];

NSIntegermyDataLength = 320 * 308 * 4;

//allocate array and read pixels into it.

GLubyte*buffer = (GLubyte *) malloc(myDataLength);

glReadPixels(0,0, 320, 308, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

//gl renders "upside down" so swap top to bottom into new array.

//there's gotta be a better way, but this works.

GLubyte*buffer2 = (GLubyte *) malloc(myDataLength);

for(inty = 0; y <308; y++){

for(intx = 0; x <320 * 4; x++){

if(buffer[y*4 * 320 + x]==0)

buffer2[(307- y) * 320 * 4 + x]=1;

else

buffer2[(307- y) * 320 * 4 + x] = buffer[y* 4 * 320 + x];

}

}

//make data provider with data.

CGDataProviderRefprovider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

//prep the ingredients

intbitsPerComponent = 8;

intbitsPerPixel = 32;

intbytesPerRow = 4 * 320;

CGColorSpaceRefcolorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGBitmapInfobitmapInfo = kCGBitmapByteOrderDefault;

CGColorRenderingIntentrenderingIntent = kCGRenderingIntentDefault;

//make the cgimage

CGImageRefimageRef = CGImageCreate(320, 308, bitsPerComponent, bitsPerPixel, bytesPerRow,colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

//then make the uiimage from that

UIImage*myImage = [UIImage imageWithCGImage:imageRef];

UIImageWriteToSavedPhotosAlbum(myImage,nil, nil, nil);

returnmyImage;

}

3.

// get screen

- (void)grabScreen {

unsignedchar buffer[320*480*4];

glReadPixels(0,0,320,480,GL_RGBA,GL_UNSIGNED_BYTE,&buffer);

CGDataProviderRefref = CGDataProviderCreateWithData(NULL, &buffer, 320*480*4, NULL);

CGImageRefiref =CGImageCreate(320,480,8,32,320*4,CGColorSpaceCreateDeviceRGB(),kCGBitmapByteOrderDefault,ref,NULL,true,kCGRenderingIntentDefault);

CGFloatwidth = CGImageGetWidth(iref);

CGFloatheight = CGImageGetHeight(iref);

size_tlength = width*height*4;

uint32_t*pixels = (uint32_t *)malloc(length);

CGContextRefcontext = CGBitmapContextCreate(pixels, width, height, 8, 320*4,CGImageGetColorSpace(iref), kCGImageAlphaLast | kCGBitmapByteOrder32Big);

CGContextTranslateCTM(context,0.0, height);

CGContextScaleCTM(context,1.0, -1.0);

CGContextDrawImage(context,CGRectMake(0.0, 0.0, width, height), iref);

CGImageRefoutputRef = CGBitmapContextCreateImage(context);

UIImage*outputImage = [UIImage imageWithCGImage:outputRef];

UIImageWriteToSavedPhotosAlbum(outputImage,nil, nil, nil);

CGContextRelease(context);

CGImageRelease(iref);

CGDataProviderRelease(ref);

}

4.

CGImageRefUIGetScreenImage();

voidSaveScreenImage(NSString *path){

NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];

CGImageRefcgImage = UIGetScreenImage();

void*imageBytes = NULL;

if(cgImage == NULL) {

CGColorSpaceRefcolorspace = CGColorSpaceCreateDeviceRGB();

imageBytes= malloc(320 * 480 * 4);

CGContextRefcontext = CGBitmapContextCreate(imageBytes, 320, 480, 8, 320 * 4, colorspace,kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorspace);

for(UIWindow *window in [[UIApplication sharedApplication] windows]) {

CGRectbounds = [window bounds];

CALayer*layer = [window layer];

CGContextSaveGState(context);

if([layer contentsAreFlipped]) {

CGContextTranslateCTM(context,0.0f, bounds.size.height);

CGContextScaleCTM(context,1.0f, -1.0f);

}

[layerrenderInContext:(CGContextRef)context];

CGContextRestoreGState(context);

}

cgImage= CGBitmapContextCreateImage(context);

CGContextRelease(context);

}

NSData*pngData = UIImagePNGRepresentation([UIImage imageWithCGImage:cgImage]);

CGImageRelease(cgImage);

if(imageBytes)

free(imageBytes);

[pngDatawriteToFile:path atomically:YES];

[poolrelease];

}

5.

+(UIImage *)imageWithScreenContents{

CGImageRef cgScreen = UIGetScreenImage();

if (cgScreen) {

UIImage *result = [UIImage imageWithCGImage:cgScreen];

CGImageRelease(cgScreen);

return result;

}

return nil;

}

在程序中如何把两张图片合成为一张图片

- (UIImage*)addImage:(UIImage *)image1 toImage:(UIImage *)image2{

UIGraphicsBeginImageContext(image1.size);

//Draw image1

[image1drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];

//Draw image2

[image2drawInRect:CGRectMake(0, 0, image2.size.width,image2.size.height)];

UIImage*resultingImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returnresultingImage;

}

图片:iPhone几种截屏的代码分享.jpg

iOS开发之Objective-C与JavaScript的交互

UIWebView是iOS最常用的SDK之一,它有一个stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS中与UIWebView中的网页元素交互。

stringByEvaluatingJavaScriptFromString

使用stringByEvaluatingJavaScriptFromString方法,需要等UIWebView中的页面加载完成之后去调用。我们在界面上拖放一个UIWebView控件。在Load中将google mobile加载到这个控件中,代码如下:

- (void)viewDidLoad{

[super viewDidLoad];

webview.backgroundColor= [UIColor clearColor];

webview.scalesPageToFit=YES;

webview.delegate=self;

NSURL *url =[[NSURLalloc]initWithString:@"http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp"];

NSURLRequest*request = [[NSURLRequest alloc] initWithURL:url];

[webviewloadRequest:request];

}

我们在webViewDidFinishLoad方法中就可以通过javascript操作界面元素了。

1、获取当前页面的url。

-(void)webViewDidFinishLoad:(UIWebView *)webView {

NSString *currentURL= [webViewstringByEvaluatingJavaScriptFromString:@"document.location.href"];

2、获取页面title:

NSString *title =[webview stringByEvaluatingJavaScriptFromString:@"document.title"];

3、修改界面元素的值。

NSString *js_result= [webViewstringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];

4、表单提交:

NSString *js_result2= [webViewstringByEvaluatingJavaScriptFromString:@"document.forms[0].submit();"];

这样就实现了在google搜索关键字:“朱祁林”的功能。

5、插入js代码

上面的功能我们可以封装到一个js函数中,将这个函数插入到页面上执行,代码如下:

if ([title compare:@"Google"]==NSOrderedSame) {

[webViewstringByEvaluatingJavaScriptFromString:@"var script =document.createElement('script');"

"script.type ='text/javascript';"

"script.text =\"function myFunction() { "

"var field =document.getElementsByName('q')[0];"

"field.value='朱祁林';"

"document.forms[0].submit();"

"}\";"

"document.getElementsByTagName('head')[0].appendChild(script);"];

[webViewstringByEvaluatingJavaScriptFromString:@"myFunction();"];

}

看上面的代码:

a、首先通过js创建一个script的标签,type为'text/javascript'。

b、然后在这个标签中插入一段字符串,这段字符串就是一个函数:myFunction,这个函数实现google自动搜索关键字的功能。

c、然后使用stringByEvaluatingJavaScriptFromString执行myFunction函数。

演示:第一步打开googlemobile网站

第二步输入关键字

第三步搜素

总结:这篇文章主要是讲解了stringByEvaluatingJavaScriptFromString的用法,它的功能非常的强大,用起来非常简单,通过它我们可以很方便的操作uiwebview中的页面元素。

关于iCloud的注册,到代码的实现

iCloud需要xcode4.2 IOS5 sdk 请先做好准备工作:

1.需要传件一个新的app id,要是有了一个的话,保证着个app id不是一个通配符的那种。

2.创建完成之后,你要做的是开启这项功能,就跟开发推送一样,然后在创建一个新的Provisional Profile

3.选择工程的summary,滚动到entitlement点击entitlements,xcode会自动的创建一个*.entitlements

4.点击创建的*.entitlements,分别把pist列表里的三个字段都添上内容,格式为 (Team_ID.com.yourcompany.icloudtest),不要把team_id跟 app_id弄混了啊,team_id是你创建完Provisional的时候,在最前面显示的那10个字符。

5.然后就可以在delegate里面写下面的代码了

-(BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

// Override pointfor customization after application launch.

self.window =[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

NSFileManager*fileManager = [NSFileManager defaultManager];

// Team-ID + BundleIdentifier

NSURL *iCloudURL =[fileManagerURLForUbiquityContainerIdentifier:@"ZZZZ826ZZ2.com.yourcompany.icloudtest"];

NSLog(@"%@",[iCloudURL absoluteString]);

NSUbiquitousKeyValueStore*cloudStore = [NSUbiquitousKeyValueStore defaultStore];

[cloudStoresetString:[iCloudURL absoluteString] forKey:@"iCloudURL"];

[cloudStoresynchronize]; // Important as it stores the values you set before on iCloud

UILabel *myLabel =[[UILabel alloc]initWithFrame:CGRectMake(0,round(self.window.bounds.size.height/4.0),self.window.bounds.size.width,round(self.window.bounds.size.height/8.0))];

myLabel.font =[UIFont fontWithName:@"Marker Felt" size:round(self.window.bounds.size.width/20.0)];

myLabel.numberOfLines= 4;

myLabel.text =[@"iCloudURL=" stringByAppendingFormat:@"%@", [cloudStorestringForKey:@"iCloudURL"]];

myLabel.backgroundColor= [UIColor clearColor];

myLabel.textColor =[UIColor whiteColor];

myLabel.textAlignment= UITextAlignmentCenter;

[self.windowaddSubview:myLabel];

[self.windowmakeKeyAndVisible];

return YES;

}

美化UILabel中的字体代码分享

一个UILabel中美化字体的例子,效果如下图:

附件:  UILabel.zip (29 K) 下载次数:40

改变键盘的颜色

1.只有这2种数字键盘才有效果。UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

2. 。keyboardAppearance = UIKeyboardAppearanceAlert

- (void)textViewDidBeginEditing:(UITextView *)textView{

NSArray *ws = [[UIApplicationsharedApplication] windows];

for(UIView *w in ws){

NSArray*vs = [w subviews];

for(UIView*v in vs){

if([[NSStringstringWithUTF8String:object_getClassName(v)]isEqualToString:@"UIKeyboard"]){

v.backgroundColor= [UIColor redColor];

}

}

}

}图片:改变键盘颜色.png

iOS开发之详解剪贴板

在iOS中,可以使用剪贴板实现应用程序之中以及应用程序之间实现数据的共享。比如你可以从iPhone QQ复制一个url,然后粘贴到safari浏览器中查看这个链接的内容。

概述

在iOS中下面三个控件,自身就有复制-粘贴的功能:

1、UITextView

2、UITextField

3、UIWebView

UIKit framework提供了几个类和协议方便我们在自己的应用程序中实现剪贴板的功能。

1、UIPasteboard:我们可以向其中写入数据,也可以读取数据

2、UIMenuController:显示一个快捷菜单,用来复制、剪贴、粘贴选择的项。

3、UIResponder中的 canPerformAction:withSender:用于控制哪些命令显示在快捷菜单中。

4、当快捷菜单上的命令点击的时候,UIResponderStandardEditActions将会被调用。

下面这些项能被放置到剪贴板中

1、UIPasteboardTypeListString —   字符串数组, 包含kUTTypeUTF8PlainText

2、UIPasteboardTypeListURL —   URL数组,包含kUTTypeURL

3、UIPasteboardTypeListImage —   图形数组, 包含kUTTypePNG和kUTTypeJPEG

4、UIPasteboardTypeListColor —   颜色数组

剪贴板的类型分为两种:

系统级:使用UIPasteboardNameGeneral和UIPasteboardNameFind,系统级应用程序关闭,或者卸载的数据不会丢失。

应用程序级:通过设置,可以让数据在应用程序关闭之后仍然保存在剪贴板中,但是应用程序卸载之后数据就会失去。我们可用通过pasteboardWithName:create:来创建。

了解这些之后,下面通过一系列的例子来说明如何在应用程序中使用剪贴板。

例子:

一、复制剪贴文本。

下面通过一个例子,可以在tableview上显示一个快捷菜单,上面只有复制按钮,复制tableview上的数据之后,然后粘贴到title上。

定义一个单元格类CopyTableViewCell,在这个类的上显示快捷菜单,实现复制功能。

@interfaceCopyTableViewCell : UITableViewCell {

id delegate;

}

@property(nonatomic, retain) id delegate;

@end

实现CopyTableViewCell,实现粘贴:

view plain

#import "CopyTableViewCell.h"

@implementation CopyTableViewCell

@synthesize delegate;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier(NSString *)reuseIdentifier {    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {

}

return self;

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

[super setSelected:selected animated:animated];

}

- (void)setHighlighted:(BOOL)highlighted animated(BOOL)animated {      [[self delegate] performSelector:@selector(showMenu:)                             withObject:self afterDelay:0.9f];      [super setHighlighted:highlighted animated:animated];  }  - (BOOL)canBecomeFirstResponder   {      return YES;  }  - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{      if (action == @selector(cut:)){          return NO;      }       else if(action == @selector(copy:)){          return YES;      }       else if(action == @selector(paste:)){          return NO;      }       else if(action == @selector(select:)){          return NO;      }       else if(action == @selector(selectAll:)){          return NO;      }      else       {          return [super canPerformAction:action withSender:sender];      }  }  - (void)copy:(id)sender {      UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];      [pasteboard setString:[[self textLabel]text]];  }  - (void)dealloc {      [super dealloc];  }  @end

定义CopyPasteTextController

view plain

[list=1]@interface CopyPasteTextController : UIViewController<UITableViewDelegate> {      //用来标识是否显示快捷菜单      BOOL menuVisible;      UITableView *tableView;  }  @property (nonatomic, getter=isMenuVisible) BOOL menuVisible;  @property (nonatomic, retain) IBOutlet UITableView *tableView;  @end

实现CopyPasteTextController:

view plain

#import "CopyPasteTextController.h"  #import "CopyTableViewCell.h"  @implementation CopyPasteTextController  @synthesize menuVisible,tableView;  - (void)viewDidLoad {      [super viewDidLoad];      [self setTitle:@"文字复制粘贴"];      //点击这个按钮将剪贴板的内容粘贴到title上      UIBarButtonItem *addButton = [[[UIBarButtonItem alloc]                                         initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh                                        target:self                                        action:@selector(readFromPasteboard:)]                                        autorelease];      [[self navigationItem] setRightBarButtonItem:addButton];  }  // Customize the number of sections in the table view.  - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  {      return 1;  }  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {      return 9;  }  // Customize the appearance of table view cells.  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {      static NSString *CellIdentifier =@"Cell";      CopyTableViewCell *cell = (CopyTableViewCell *)[tableView                                                              dequeueReusableCellWithIdentifier:CellIdentifier];      if (cell == nil)       {          cell = [[[CopyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];          [cell setDelegate:self];      }      // Configure the cell.      NSString *text = [NSString stringWithFormat:@"Row %d", [indexPath row]];      [[cell textLabel] setText:text];      return cell;  }  - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {      if([self isMenuVisible])      {          return;      }      [[[self tableView] cellForRowAtIndexPath:indexPath] setSelected:YES                                                              animated:YES];  }  //显示菜单  - (void)showMenu:(id)cell {      if ([cell isHighlighted]) {          [cell becomeFirstResponder];          UIMenuController * menu = [UIMenuController sharedMenuController];          [menu setTargetRect: [cell frame] inView: [self view]];          [menu setMenuVisible: YES animated: YES];      }  }  - (void)readFromPasteboard:(id)sender {      [self setTitle:[NSString stringWithFormat:@"Pasteboard = %@",                         [[UIPasteboard generalPasteboard] string]]];  }  - (void)didReceiveMemoryWarning  {      // Releases the view if it doesn't have a superview.      [super didReceiveMemoryWarning];      // Relinquish ownership any cached data, images, etc that aren't in use.  }  - (void)viewDidUnload  {      [super viewDidUnload];      [self.tableView release];      // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.      // For example: self.myOutlet = nil;  }

效果:

复制一行数据:

点击右上角的按钮粘贴,将数据显示在title上:

二、图片复制粘贴

下面通过一个例子,将图片复制和剪贴到另外一个UIImageView中间。

1、在界面上放置两个uiimageview,一个是图片的数据源,一个是将图片粘贴到的地方。CopyPasteImageViewController 代码如下:

view plain

@interface CopyPasteImageViewController : UIViewController {      UIImageView *imageView;      UIImageView *pasteView;      UIImageView *selectedView;  }  @property (nonatomic, retain) IBOutlet UIImageView *imageView;  @property (nonatomic, retain) IBOutlet UIImageView *pasteView;  @property (nonatomic, retain) UIImageView *selectedView;  - (void)placeImageOnPasteboard:(id)view;  @end

2、当触摸图片的时候我们显示快捷菜单:

view plain

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {      NSSet *copyTouches = [event touchesForView:imageView];      NSSet *pasteTouches = [event touchesForView:pasteView];      [self becomeFirstResponder];      if ([copyTouches count] > 0) {          [self performSelector:@selector(showMenu:)                      withObject:imageView afterDelay:0.9f];      }      else  if([pasteTouches count] > 0) {          [self performSelector:@selector(showMenu:)                      withObject:pasteView afterDelay:0.9f];      }      [super touchesBegan:touches withEvent:event];  }  - (void)showMenu:(id)view {      [self setSelectedView:view];      UIMenuController * menu = [UIMenuController sharedMenuController];      [menu setTargetRect: CGRectMake(5, 10, 1, 1) inView: view];      [menu setMenuVisible: YES animated: YES];  }

这里的快捷菜单,显示三个菜单项:剪贴、粘贴、复制:

view plain

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{      if (action == @selector(cut:)) {          return ([self selectedView] == imageView) ? YES : NO;      } else if (action == @selector(copy:)) {          return ([self selectedView] == imageView) ? YES : NO;      } else if (action == @selector(paste:)) {          return ([self selectedView] == pasteView) ? YES : NO;      } else if (action == @selector(select:)) {          return NO;      } else if (action == @selector(selectAll:)) {          return NO;      } else {          return [super canPerformAction:action withSender:sender];      }  }  - (void)cut:(id)sender {      [self copy:sender];      [imageView setHidden:YES];  }  - (void)copy:(id)sender {      [self placeImageOnPasteboard:[self imageView]];  }  - (void)paste:(id)sender {      UIPasteboard *appPasteBoard =       [UIPasteboard pasteboardWithName:@"CopyPasteImage" create:YES];      NSData *data =[appPasteBoard dataForPasteboardType:@"com.marizack.CopyPasteImage.imageView"];      pasteView.image = [UIImage imageWithData:data];  }

效果:

1、点击图片,显示菜单按钮。

2、点击复制,将数据复制到剪贴板上:

3、点击粘贴,将数据粘贴到uiimageview上。

优化iPhone中大数据量列表的加载

这几天在研究如何优化大数据列表的显示,在网上找到这篇文章。文章写于2009年,可能有点老了,但还是有些借鉴意义,所以把它翻了过来,与大家一起分享。可惜的是作者没有提供相应的原代码。

在这篇文章中,我们将看到一个iPhone中从服务器加载数据的UITableView及当数据量从1到成千上万行时UITableView的表现。我将测试当显示数据集从很小到很大时哪种方法表现良好,而哪种方法表现拙劣。

介绍

上周,我收到一封邮件,问我StreamToMe在一个中间集合中是否可以处理20,000个文件。这位仁兄可能是问“20,000个文件分类进子目录中”,但是我立即想到将20,000个文件放到一个单独目录中是一个更有趣的问题。

我们在iPhone应用程序中可以很容易的发现当table只处理几百行数据时,程序会变得很慢,响应迟钝。在我的经历中,我很少去测试在一个UITableView旋转几百行数据。我不知道当有20,000行数据时,UITableView会怎么样。

单纯从数据量上看,它应该能正常工作:128MB的iPhone版本(所有早于3Gs的版本)允许应用程序使用24MB-64MB的内存,直到被系统强制关闭。这就允许每一行的数据使用1-3kB的内存—事实上,我不需要这么多。

当然,这并不是有效的综合测试。下面这个程序将进行实际的测试,真实的数据、服务器交互、解析、构造和显示,在所有的东西加载进内存后还必须能回放音频。

http://www.cocoachina.com/newbie/basic/2011/1213/3713.html

iphone之启动界面

在iphone的启动应用之前,系统会默认在Resources文件夹中的Default.png,为启动界面。

为了在iPad上使用上述的启动画面,你还需要在info.plist中加入

key: UISupportedInterfaceOrie

ntations。

同时,加入值

UIInterfaceOrientationPortrait

UIInterfaceOrientationPortraitUpsideDown

UIInterfaceOrientationLandscapeLeft

UIInterfaceOrientationLandscapeRight。

如果觉的启动界面时间比较短,也可以加入下面代码控制一下:

代码如下;

-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

[NSThread  sleepForTimeInterval:3];

returnYES;

}

iphone项目的启动界面尺寸设为320x480,系统自带的,进行加载。

格式和尺寸

图标和启动画面的图片格式:推荐使用PNG格式,可以是标准的24位色,外加alpha通道的8位。

iPhone/iPod Touch的启动画面是全尺寸,iPad的则要去掉状态栏的高度20px。

iPad的启动画面是分模式的:竖排(portrait)和横排(landscape)。

iPhone4和ipod Touch4有一个新特性:在屏幕尺寸不变的前提下,分辨率提升一倍(320x480=>640x960)。此特性苹果命名为Retina。

因此如果app要支持Retina,就要提供分辨率宽高各增一倍的图片,且为了兼顾没有Retina的设备,原来低分辨率的图片仍然要提供 。针对不同分辨率的相同图片,苹果规定的命名规则是:高分辨率的文件名比普通分辨率的文件名多“@2x”字样。

MBProgressHUD的使用

1。 网上下载  MBProgessHUD 类,导入到工程。

https://github.com/jdg/MBProgressHUD2。#import "MBProgressHUD.h"

类实现 MBProgressHUDDelegate 代理。

3。 在类里面定义:

MBProgressHUD* progress_;

4。 显示;

view plain

progress_ = [[MBProgressHUD alloc] initWithView:self.tableView];  [self.view addSubview:progress_];  [self.view bringSubviewToFront:progress_];  progress_.delegate = self;  progress_.labelText = @"加载中...";  [progress_ show:YES];

隐藏:

viewplain

if (progress_)   {      [progress_ removeFromSuperview];      [progress_ release];      progress_ = nil;  }

5。实现协议:

viewplain

- (void)hudWasHidden:(MBProgressHUD *)hud   {      NSLog(@"Hud: %@", hud);      // Remove HUD from screen when the HUD was hidded    [progress_ removeFromSuperview];      [progress_ release];      progress_ = nil;  }

搜狗手机输入法iPhone 版宣布开放 App 集成接口

一直以来,iOS 平台(尤其是 iPhone 和 iPod touch)上的中文输入法都是一大诟病,苹果官方又一直不开放第三方输入法的接口,导致国内优秀的中文输入法(如搜狗、QQ、百度)都必须对设备进行越狱之后才能通过非官方的 Cydia 平台安装,因此一些公司开始在应用程序中直接内置“应用级”的输入法,比如最新的 QQ for iPhone 就已经内置了 QQ 输入法,但只能在这一个应用中才能使用。

今天,搜狗输入法团队在官方微博上宣布开放搜狗手机输入法 iPhone 版的 App 集成接口,iPhone 应用开发者如果有输入法集成需要的话,只需登陆搜狗手机输入法官网提出申请,经审核合格后即可免费在其 App 应用中内置搜狗手机输入法iPhone 版,这无疑给很多国内的开发者提供了一个非常优秀的解决输入法问题的方案。

目前,搜狗手机输入法iPhone 版开放接口已经有成功应用案例——搜狐微博搜狗输入版。

但是,即便是搜狗开放了该接口,对于绝大部分应用(包括苹果自家的短信、备忘录等等)来说仍然只能使用 iPhone 内置的“难用至极”的默认输入法,所以要想从根本上解决 iPhone 上中文输入法的问题,还是只能等苹果官方开放相应的权限,但由于这是系统层级的操作,苹果很有可能永远都不会开放。

访问:搜狗手机输入法 iPhone版开放平台

iOS/iPhone学习系列、代码教程

http://www.devdiv.com/iOS_iPhone-iOS_iPhone%E5%AD%A6%E4%B9%A0%E7%B3%BB%E5%88%97%E3%80%81%E4%BB%A3%E7%A0%81%E6%95%99%E7%A8%8B----___%E6%8C%81%E7%BB%AD%E6%9B%B4%E6%96%B0%E4%B8%AD___-thread-48165-1-1.html

iPhone上实现Default.png动画

18.        原理:

19.        添加一张和Default.png一样的图片,对这个图片进行动画,从而实现Default动画的渐变消失的效果。

20.        操作:

21.        在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions中添加如下代码:

22.        // Make this interesting.

23.            UIImageView *splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 320, 480)];

24.            splashView.image = [UIImage imageNamed:@"Default.png"];

25.            [self.window addSubview:splashView];

26.            [self.window bringSubviewToFront:splashView];

27.            [UIView beginAnimations:nil context:nil];

28.            [UIView setAnimationDuration:2.0];

29.            [UIView setAnimationTransition:UIViewAnimationTransitionNone forView: self.window cache:YES];

30.            [UIView setAnimationDelegate:self];

31.            [UIView setAnimationDidStopSelector:@selector(startupAnimationDone:finished:context:)];

32.            splashView.alpha = 0.0;

33.            splashView.frame = CGRectMake(-60, -85, 440, 635);

34.            [UIView commitAnimations];

就ok了

介绍UIALertView和UIActionSheet的用法。

write by Xingchen’ssky

1:构建一个简单的警告框:

UIAlertView*alert=[[UIAlertViewalloc] initWithTitle:@"xingchen"

message:@"message"

delegate:nil

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[alert show];

[alert release];

这里,仅仅是现实一个按钮的对话框,以模态的形式运行。

2:当然,我们可以在一个alertView中添加多个按钮,参考代码如下所示:

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"xingchen"

message:@"message"

delegate:nil

cancelButtonTitle:@"OK"

otherButtonTitles:@"FirstButton",@"SecondButton",

nil];

[alert show];

[alert release];

3:判断单击来那个按钮,并根据不同的按钮触发不同的事件:

alertView有一个委托(UIAlertViewDelegate),我们可以继承他,然后调用该委托来处理事件

参考代码

UIAlertView *alert =[[UIAlertViewalloc] initWithTitle:@"xingchen"

message:@"message" delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:@"FirstButton",

@"SecondButton",nil];

[alert show];

[alert release];

//delegate

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(int)index

{

NSString *tt = [[NSStringalloc]initWithFormat:@"%d",index];

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"xingchen"

message:tt

delegate:self

cancelButtonTitle:@"OK"

otherButtonTitles:nil];

[alert show];

[alert release];

}

4:手动的取消对话框

参考代码:

[alertdismissWithClickedButtonIndex:0animated:YES];

5:为UIAlertView添加子视图

在为UIAlertView对象太添加子视图的过程中,有点是需要注意的地方,如果删除按钮,也就是取消UIAlerView视图中所有的按钮的时候,可能会导致整个显示结构失衡。按钮占用的空间不会消失,我们也可以理解为这些按钮没有真正的删除,仅仅是他不可见了而已。如果在UIAlertview对象中仅仅用来显示文本,那么,可以在消息的开头添加换行符(@"\n)有助于平衡按钮底部和顶部的空间。

下面的代码用来演示如何为UIAlertview对象添加子视图的方法。

-(IBAction)showAlert

{

UIAlertView *alert =[[UIAlertViewalloc]initWithTitle:@"xingchen"message:nildelegate:nil

cancelButtonTitle:nilotherButtonTitles:nil];

[alert show];

UIActivityIndicatorView*activeView= [[UIActivityIndicatorView alloc]

initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

activeView.center=CGPointMake(alert.bounds.size.width/2.0f, alert.bounds.size.height-40.0f);

[activeViewstartAnimating];

[alertaddSubview:activeView];

[activeViewrelease];

[alert release];

}

显示效果如下所示:

6:UIActionSheet

UIActionSheet也是一个模态对话框,提供类似于菜单的功能,供用户进行选择,参考代码如下所示:

-(IBAction)showAlert

{

UIActionSheet *sheet=[[UIActionSheet alloc] initWithTitle:@"ActionSheetTitle"

delegate:nil

cancelButtonTitle:@"Cancel"

destructiveButtonTitle:nil

otherButtonTitles:@"FirstButton",@"SecondButton",@"thirdButton",nil];

[sheetshowInView:[self view]];

[sheet release];

}

[sheet showInView:[selfview]];表示该UIActionsheet在那个视图里面显示。

他有一个委托是:UIActionSheetDelegate

委托的函数:

@protocolUIActionSheetDelegate<NSObject>

@optional

//Called when abutton is clicked. The view will be automaticallydismissed after this call returns

-(void)actionSheet:(UIActionSheet*)actionSheetclickedButtonAtIndex:(NSInteger)buttonIndex;

//Called when wecancel a view (eg. the user clicks the Home button).This is not called when theuser clicks the cancel button.

// Ifnot defined inthe delegate, we simulate a click in the cancelbutton

-(void)actionSheetCancel:(UIActionSheet*)actionSheet;

-(void)willPresentActionSheet:(UIActionSheet*)actionSheet; // before animation and showing view

-(void)didPresentActionSheet:(UIActionSheet*)actionSheet; // after animation

-(void)actionSheet:(UIActionSheet*)actionSheetwillDismissWithButtonIndex:(NSInteger)buttonIndex; //beforeanimation and hiding view

-(void)actionSheet:(UIActionSheet*)actionSheetdidDismissWithButtonIndex:(NSInteger)buttonIndex;  // afteranimation

@end

7:Please wait ;向用户显示进度。

等待是计算机用户体验的一个部分,iphone也需要在某些情况下告知用户你所需要的数据正在加载过程中,请用户耐心等待,并需要让用户看到iphone当前确实在运行而不是已经死机。在iphone有2中有两种方式来达到该效果

UIActivityIndicatorView和UIActionSheet

8:UIProgressBar

一个显示进度的进度条控件,他可以让用户看到程序工作的进度,指示任务完成的程度。

9:使用网络指示器:

UIApplication *app=[UIApplication sharedApplication];

app.networkActivityIndicatorVisible=!app.networkActivityIndicatorVisible;

http://blog.sina.com.cn/s/blog_6effdb920100vntz.html

Iphone显示“正在加载”

 ActivityView.h

#import

 #define kAnimationDurationStart 2

#definekAnimationDurationEnd 1

@interface ActivityView : NSObject {

IBOutlet UILabel *messageLabel;

IBOutlet UIView *view;

BOOLisShow;

}

 @property(nonatomic, readonly) UILabel *messageLabel;

 @property(nonatomic, readonly) UIView *view; 

@property(nonatomic) BOOL isShow; 

+ (ActivityView*)sharedActivityView;  

 -(void)showWithMessage:(NSString *)message animate:(BOOL)animate; 

 -(void)hide:(BOOL)animate;

@end

ActivityView.m

#import"ActivityView.h" 

 @implementationActivityView 

 @synthesizemessageLabel,view, isShow;  

 //单例模式  

static ActivityView*activityView;  

 - (id)init { 

 self =[super init]; 

 if(self != nil) { 

  [[NSBundle mainBundle] loadNibNamed:@"ActivityView" owner:selfoptions:nil]; 

  [[[UIApplication sharedApplication] keyWindow] addSubview:view];  

[view setFrame:CGRectMake(0,[UIApplicationsharedApplication].statusBarFrame.size.height-view.frame.size.height,view.frame.size.width, view.frame.size.height)]; 

  isShow = NO;  

}  return self; 

 }  

 +(ActivityView *)sharedActivityView { 

 if (!activityView) {  

activityView = [[ActivityView alloc]init];  

}  

return activityView; 

 }  

 -(void)showWithMessage:(NSString *)message animate:(BOOL)animate { 

 isShow = YES; 

 messageLabel.text = message; 

 [view.superview bringSubviewToFront:view];

}

http://www.iappex.com/

如何在UIAlertView中显示进度条

http://www.cocoachina.com/iphonedev/toolthain/2011/1223/3778.html

图片:在UIAlertView中显示进度条.png

iPhone键盘改变颜色

只有这2种数字键盘才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad

keyboardAppearance = UIKeyboardAppearanceAlert

代码如下:

NSArray*ws = [[UIApplication sharedApplication] windows];

for(UIView *w in ws){

NSArray*vs = [w subviews];

for(UIView*v in vs){

if([[NSStringstringWithUTF8String:object_getClassName(v)]isEqualToString:@"UIKeyboard"]){

v.backgroundColor= [UIColor redColor];

}

}

}

从一个界面push到下一界面左上角返回按钮文字设置(常用功能)

//在父viewController中如下设置:

UIBarButtonItem*backbutton = [[UIBarButtonItem alloc]init];

backbutton.title= @"返回列表";

self.navigationItem.backBarButtonItem= backbutton;

[backbuttonrelease];

//navigationbar的back键触发其他事件

UIButton *back=[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)];

[back addTarget:selfaction:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside];

[backsetImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];

UIBarButtonItem*backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back];

self.navigationItem.leftBarButtonItem= loginButtonItem

[back release];

[backButtonItemrelease];

大屏日历异步加载每天比赛数目并显示在日历里

#import <QuartzCore/QuartzCore.h> 

  #import "CalendarController.h"

 #import "TdCalendarView.h"

 #import "WaitDialog.h"

 #import "JSONParser.h"

 #import "FunUtil.h"

@implementation CalendarController 

@synthesize calendarView; 

@synthesize currentSelectDate; 

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  

    if (self) {  

        self.title = @"比赛时间";  

        //self.view.backgroundColor = [UIColor whiteColor];  

        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back.png"]];   

        calendarView = [[TdCalendarView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];  

        calendarView.backgroundColor = [UIColor whiteColor];  

        //calendarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back.png"]];   

        [self.view addSubview:calendarView];  

        [calendarView setDayFlag:15 flag:-1];  

        calendarView.calendarViewDelegate = self;  

    }  

    return self;  

}  

 

- (void) selectDateChanged:(CFGregorianDate) selectDate{  

    currentSelectDate = selectDate;  

    NSLog(@"selectDateChanged catch:%d年%d月%d日",selectDate.year,selectDate.month,selectDate.day);  

}  

- (void) monthChanged:(CFGregorianDate) currentMonth viewLeftTop:(CGPoint)viewLeftTop height:(float)height{  

    NSLog(@"monthChanged catch:%d",currentMonth.month);  

    self.currentSelectDate = currentMonth;

    [NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil];//创建一个线程

}  

- (void) beforeMonthChange:(TdCalendarView*) calendarView willto:(CFGregorianDate) currentMonth{  

    [[self calendarView] clearAllDayFlag];  

}  

/*  

// Only override drawRect: if you perform custom drawing.  

// An empty implementation adversely affects performance during animation.  

- (void)drawRect:(CGRect)rect {  

    // Drawing code.  

}  

*/  

 

- (void)viewDidAppear:(BOOL)animated{  

    [super viewDidAppear:animated]; 

}  

-(void)fetchdata{  

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;  

    int maxDay = [[self calendarView] getDayCountOfaMonth:currentSelectDate];  

    NSString *dataURL =@"";  

    NSLog(@"dataURL:%@",dataURL);  

    NSArray *data = [JSONParser loadData:dataURL isAllValues:NO valueForKey:@"list"];  

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  

    [self performSelectorOnMainThread:@selector(showCount:) withObject:data waitUntilDone:NO];//通知主线程执行函数showCount

    [pool release];  

}  

-(void)showCount:(NSArray *)data{  

    int count = [data count];  

    NSLog(@"showChange:%d",count);  

    for(int i = 0;i<count-1;i++){  

        NSArray *bf = [data objectAtIndex:i];  

        if([bf valueForKey:@"day"]!=nil){  

            int day = [[bf valueForKey:@"day"]intValue];  

            int count = [[bf valueForKey:@"count"]intValue];  

            [calendarView setDayFlag:day flag:count];  

        }  

    }  

    [calendarView setNeedsDisplay];  

}  

 

- (void)dealloc {  

    [calendarView release];  

    [super dealloc];  

}  

@end  

当一个View将要展现时触发该方法,可在该方法中准备将要展现到VIEW中的数据,比如重连数据库读取数据到NSMutableArray中然后通过[tableView reloadData]刷新tableView的显示内容!

 

View A跳转方法

addStudentViewController*add; //View B

-(IBAction)addClicked:(id)sender{

      add=[[addStudentViewControlleralloc]initWithNibName:@"addStudent" bundle:nil];

     [self.view addSubview:add.view]; 

}

//ViewB 中的退出方法

-(IBAction)doneBtnClicked:(id)sender{

      [self.view removeFromSuperview];

}

 

以下方法实现View跳转则触发!

-------------------------------------

View A跳转方法

addStudentViewController*add; //View B

-(IBAction)addClicked:(id)sender{

     add=[[addStudentViewControlleralloc]initWithNibName:@"addStudent" bundle:nil];

     [self presentModalViewController:add animated:YES];

}

View B中的退出方法

-(IBAction)doneBtnClicked:(id)sender{

    [self.parentViewControllerdismissModalViewControllerAnimated:YES];

}

程序启动时候自定义的显示页面

//PRPSplashScreenDelegate.h

@classPRPSplashScreen;

@protocol PRPSplashScreenDelegate<NSObject>

@optional

-(void)splashScreenDidAppear:(PRPSplashScreen*)splashScreen;

-(void)splashScreenWillDisappear:(PRPSplashScreen*)splashScreen;

-(void)splashScreenDidDisappear:(PRPSplashScreen*)splashScreen;

@end

//PRPSplashScreen.h

#import"PRPSplashScreenDelegate.h"

@interfacePRPSplashScreen : UIViewController {}

@property(nonatomic, retain) UIImage*splashImage;

@property(nonatomic, assign) BOOLshowsStatusBarOnDismissal;

@property(nonatomic, assign) IBOutletid<PRPSplashScreenDelegate>delegate;

- (void)hide;

@end

//PRPSplashScreen.m

#import"PRPSplashScreen.h"

@implementationPRPSplashScreen

@synthesizesplashImage;

@synthesizeshowsStatusBarOnDismissal;

@synthesizedelegate;

- (void)dealloc {

[splashImagerelease], splashImage = nil;

[superdealloc];

}

-(void)viewDidUnload {

[superviewDidUnload];

self.splashImage = nil;

}

- (void)loadView {

UIImageView *iv= [[UIImageView alloc] initWithImage:self.splashImage];

iv.autoresizingMask = UIViewAutoresizingFlexibleWidth|

UIViewAutoresizingFlexibleHeight;

iv.contentMode= UIViewContentModeCenter;

self.view =iv;

[ivrelease];

}

- (UIImage*)splashImage {

if(splashImage== nil) {

self.splashImage = [UIImageimageNamed:@"Default.png"];

}

returnsplashImage;

}

- (void)hide {

if(self.showsStatusBarOnDismissal)

{

UIApplication *app =[UIApplication sharedApplication];

[app setStatusBarHidden:NOwithAnimation:UIStatusBarAnimationFade];

}

[selfdismissModalViewControllerAnimated:YES];

}

-(void)viewDidAppear:(BOOL)animated {

[superviewDidAppear:animated];

SELdidAppearSelector = @selector(splashScreenDidAppear:);

if([self.delegate respondsToSelector:didAppearSelector]) {

[self.delegatesplashScreenDidAppear:self];

}

[selfperformSelector:@selector(hide) withObject:nil afterDelay:0];

}

-(void)viewWillDisappear:(BOOL)animated {

[superviewWillDisappear:animated];

if([self.delegaterespondsToSelector:@selector(splashScreenWillDisappear:)]) {

[self.delegatesplashScreenWillDisappear:self];

}

}

-(void)viewDidDisappear:(BOOL)animated {

[superviewDidDisappear:animated];

if([self.delegaterespondsToSelector:@selector(splashScreenDidDisappear:)]) {

[self.delegatesplashScreenDidDisappear:self];

}

}

@end

//AppDelagate.h

#import"PRPSplashScreen.h"

@interfaceAppDelegate_iPhone :NSObject<UIApplicationDelegate,PRPSplashScreenDelegate> {}

@property(nonatomic, retain) IBOutlet UIWindow*window;

@property(nonatomic, retain) IBOutletUINavigationController *navController;

@property(nonatomic, retain) IBOutletPRPSplashScreen *splashScreen;

@end

//AppDelagate.m

#import"AppDelegate_iPhone.h"

#import"PRPSplashScreen.h"

@implementationAppDelegate_iPhone

@synthesize window;

@synthesizenavController;

@synthesizesplashScreen;

#pragma mark -

#pragma markApplication lifecycle

-(BOOL)application:(UIApplication*)application

didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[self.windowaddSubview:self.navController.view];

self.splashScreen.showsStatusBarOnDismissal = YES;

self.splashScreen.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;

[self.navController presentModalViewController:splashScreenanimated:NO];

[self.windowmakeKeyAndVisible];

returnYES;

}

-(void)splashScreenDidAppear:(PRPSplashScreen*)splashScreen {

NSLog(@"splashScreenDidAppear!");

}

-(void)splashScreenWillDisappear:(PRPSplashScreen*)splashScreen {

NSLog(@"splashScreenWillDisappear!");

}

-(void)splashScreenDidDisappear:(PRPSplashScreen*)splashScreen {

self.splashScreen = nil;

}

- (void)dealloc {

[windowrelease], window = nil;

[navControllerrelease], navController = nil;

[splashScreenrelease], splashScreen = nil;

[superdealloc];

}

Calendar_Demo(日历)

#import<UIKit/UIKit.h>

#import<QuartzCore/QuartzCore.h>

@protocolCalendarDelegate<NSObject>

-(void)clickedCanlendarButton;

@end

@interface Calendar :UIView{

CFGregorianDatecurrentMonthDate;

CFAbsoluteTimecurrentTime;

UIImageView*viewImageView;

UIView *topView;

NSString *daydata;

NSString*saveMonthDate;

NSString *selectDay;

intupMonthDaycounts;

BOOLisContinuousClick;

int saveTodaytag;

}

@property(nonatomic,retain)NSString *selectDay;

@property   BOOLisContinuousClick;

@propertyCFGregorianDatecurrentMonthDate;

@propertyCFAbsoluteTime  currentTime;

@property(nonatomic,retain)   UIImageView    *viewImageView;

@property(nonatomic, retain) id<CalendarDelegate>delegate;

-(int)getMonthWeekday:(CFGregorianDate)date;

-(int)getDayCountOfaMonth:(CFGregorianDate)date;

-(void)drawTopWeekDay;

-(void)drawDateWords;

-(void)movePrevMonth;

-(void)moveNextMonth;

-(void)movePrevOrNextMonth:(int)isPrev;

-(void)myInit;

-(void)drawGirdLines;

-(void)dateButtonClicked:(UIButton*)buttontag;

//-(void)selectCalenda

@end

.m

#import"Calendar.h"

@implementationCalendar

@synthesizecurrentMonthDate;

@synthesizecurrentTime;

@synthesizeviewImageView;

@synthesizedelegate;

@synthesizeisContinuousClick;

@synthesizeselectDay;

intyearButtonFontSize;

int weekFontSize;

int calendarWidth;

int calendarHeight;

intyearMonthFontSize;

intcalendarFontSize;

int _height;

-(void)myInit

{

calendarWidth=320;//日历宽

calendarHeight=480;//日历高

weekFontSize=15;//星期字体大小设置

yearMonthFontSize=24;//年月标题字体大小设置

yearButtonFontSize=15;//切换上下月按钮的字体的大小

_height=calendarHeight/10;

calendarFontSize=16;//日期字体大小

}

-(id)initWithFrame:(CGRect)frame

{

self= [superinitWithFrame:frame];

if(self) {

isContinuousClick=YES;

currentTime=CFAbsoluteTimeGetCurrent();

currentMonthDate=CFAbsoluteTimeGetGregorianDate(currentTime,CFTimeZoneCopyDefault());

currentMonthDate.day=1;

NSDateFormatter*nowyearmonthday=[[NSDateFormatteralloc] init];

[nowyearmonthdaysetDateFormat:@"yyyy-MM-d"];

saveMonthDate=[[NSStringalloc]initWithString:[nowyearmonthdaystringFromDate:[NSDatedate]]];

[nowyearmonthdayrelease];

NSLog(@"saveMonthDate==%@",saveMonthDate);

[selfmyInit];

[selfdrawTopWeekDay];

[selfdrawDateWords];

[selfsetFrame:CGRectMake(0,0, 320, calendarHeight)];

[selfsetBackgroundColor:[UIColor clearColor]];

}

return self;

}

-(void)drawTopWeekDay

{

int width=calendarWidth/7;

//    //返回上个月按钮

UIButton *prevMonth = [[UIButton alloc] init];

prevMonth.frame=CGRectMake(0,0,calendarWidth/6,_height);

[prevMonthsetTitle:@"上个月"forState:UIControlStateNormal];

[prevMonth.titleLabelsetFont:[UIFont boldSystemFontOfSize:yearButtonFontSize]];

[prevMonthsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[prevMonthaddTarget:selfaction:@selector(movePrevMonth)forControlEvents:UIControlEventTouchUpInside];

[selfaddSubview:prevMonth];

//年月标题

NSString*yearMonth=[[NSString alloc]initWithFormat:@"%i年%i月",currentMonthDate.year,currentMonthDate.month];

UILabel*yearMonthLabel=[[UILabel alloc]initWithFrame:CGRectMake(calendarWidth/6,0,calendarWidth/6*4, _height)];

yearMonthLabel.textAlignment=UITextAlignmentCenter;

yearMonthLabel.textColor=[UIColorblackColor];

yearMonthLabel.backgroundColor=[UIColorclearColor];

yearMonthLabel.text=yearMonth;

yearMonthLabel.font=[UIFont systemFontOfSize:yearMonthFontSize];

[selfaddSubview:yearMonthLabel];

[yearMonth release];

[yearMonthLabel release];

//    //查看下个月按钮

UIButton *nextMonth = [[UIButton alloc] init];

[nextMonthsetTitle:@"下个月"forState:UIControlStateNormal];

[nextMonth.titleLabelsetFont:[UIFont boldSystemFontOfSize:yearButtonFontSize]];

[nextMonthsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

nextMonth.frame=CGRectMake(calendarWidth/6*5,10, calendarWidth/6, _height);

[nextMonthaddTarget:selfaction:@selector(moveNextMonth)forControlEvents:UIControlEventTouchUpInside];

[selfaddSubview:nextMonth];

//

//    //星期标题

NSArray*weekDay=[[NSArray alloc]initWithObjects:@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六", nil];

for(int i = 0; i < 7; i++) {

UILabel *weekLabel=[[UILabelalloc]initWithFrame:CGRectMake(i*width, _height, width, _height)];

weekLabel.backgroundColor=[UIColor clearColor];

weekLabel.textAlignment=UITextAlignmentCenter;

[weekLabelsetFont:[UIFontboldSystemFontOfSize:weekFontSize]];

weekLabel.textColor=[UIColorblackColor];

if (i == 0|| i == 6) {

weekLabel.textColor=[UIColor redColor];

}

weekLabel.text=[weekDay objectAtIndex:i];

[selfaddSubview:weekLabel];

[weekLabel release];

}

[weekDay release];

}

-(void)drawDateWords

{

floatheadHeight=calendarHeight/5;

floatitemHeight=40;

intcurrentMonthDaycounts=[selfgetDayCountOfaMonth:currentMonthDate];

intcurrentWeekday=[selfgetMonthWeekday:currentMonthDate]%7;

NSLog(@"currentWeekday==%d",currentWeekday);

intday=0;

int x= 0;

int y= 0;

intwidth=calendarWidth/7;

NSDateFormatter*dateFormatteryy = [[NSDateFormatteralloc] init];

NSDateFormatter*dateFormattermm = [[NSDateFormatteralloc] init];

NSDateFormatter*dateFormatterdd = [[NSDateFormatteralloc] init];

[dateFormatteryy setDateFormat:@"yyyy"];

[dateFormattermm setDateFormat:@"M"];

[dateFormatterdd setDateFormat:@"d"];

NSString *nowyear =[[NSString alloc] initWithString:[dateFormatteryystringFromDate:[NSDatedate]]];

NSString *nowmonth =[[NSString alloc] initWithString:[dateFormattermmstringFromDate:[NSDatedate]]];

NSString *tody =[[NSString alloc] initWithString:[dateFormatterddstringFromDate:[NSDatedate]]];

NSLog(@"nowmonth==%@",nowmonth);

NSLog(@"tody==%@",tody);

NSString*year=[[NSString alloc]initWithFormat:@"%i",currentMonthDate.year];

NSString *month=[[NSString alloc]initWithFormat:@"%i",currentMonthDate.month];

for(int i = 0 ; i <currentWeekday; i++) {

NSString*date=[[NSString alloc]initWithFormat:@"%i",i+upMonthDaycounts-currentWeekday+1];

UIButton*button = [[UIButtonalloc] init];

button.frame=CGRectMake((i%7)*width +4,(i/7)*itemHeight+headHeight+ 4, width-5,itemHeight-6);

[buttonsetTitle:dateforState:UIControlStateNormal];

[buttonsetTitleColor:[UIColorgrayColor]forState:UIControlStateNormal];

button.backgroundColor=[UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0];

[button.titleLabelsetFont:[UIFontboldSystemFontOfSize:calendarFontSize]];

[selfaddSubview:button];

[button release];

}

for(int i = 0;i<currentMonthDaycounts; i++) {

day=i+currentWeekday;

x=day%7;

y=day/7;

NSString*date=[[NSString alloc]initWithFormat:@"%i",i+1];

UIButton*button = [[UIButtonalloc] init];

button.tag=i+1;

//      [buttonsetBackgroundImage:[UIImageimageNamed:@"date.png"]forState:UIControlStateNormal];

button.frame=CGRectMake(x*width +5,y*itemHeight+headHeight + 4, width-6,itemHeight-7);

[buttonsetTitle:dateforState:UIControlStateNormal];

[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];

button.backgroundColor=[UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0];

[button.titleLabelsetFont:[UIFontboldSystemFontOfSize:calendarFontSize]];

[buttonaddTarget:selfaction:@selector(dateButtonClicked:)forControlEvents:UIControlEventTouchUpInside];

if ([dateisEqualToString:tody]&& [nowyearisEqualToString:year]&& [nowmonth isEqualToString:month]) {

saveTodaytag=button.tag;

[buttonsetHighlighted:YES];

button.backgroundColor= [UIColor colorWithRed:1 green:0.63 blue:0.91 alpha:0.99];

[buttonsetTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

}

[selfaddSubview:button];

[button release];

}

if((currentMonthDaycounts+currentWeekday)%7!=0) {

intnextMonthDaycounts=((currentMonthDaycounts+currentWeekday)/7+1)*7;

for(int i =currentMonthDaycounts+currentWeekday; i <nextMonthDaycounts;i ++) {

NSString *date=[[NSStringalloc]initWithFormat:@"%i",i-(currentMonthDaycounts+currentWeekday)+1];

UIButton *button =[[UIButton alloc] init];

button.frame=CGRectMake((i%7)*width +4,(i/7)*itemHeight+headHeight+ 4, width-5,itemHeight-6);

[buttonsetTitle:date forState:UIControlStateNormal];

[buttonsetTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

button.backgroundColor =[UIColor colorWithRed:0.847 green:0.847blue:0.847 alpha:1.0];

[button.titleLabelsetFont:[UIFont boldSystemFontOfSize:calendarFontSize]];

[self addSubview:button];

[buttonrelease];

}

}

[todyrelease];

[nowyear release];

[nowmonth release];

[yearrelease];

[monthrelease];

[dateFormatteryy release];

[dateFormattermm release];

[dateFormatterdd release];

}

-(int)getDayCountOfaMonth:(CFGregorianDate)date

{

switch(date.month) {

case 1:

upMonthDaycounts=31;

break;

case 2:

upMonthDaycounts=31;

break;

case 3:

if (date.year%4==0&&date.year!=0){

upMonthDaycounts=29;

}else{

upMonthDaycounts=28;

}

break;

case 4:

upMonthDaycounts=31;

break;

case 5:

upMonthDaycounts=30;

break;

case 6:

upMonthDaycounts=31;

break;

case 7:

upMonthDaycounts=30;

break;

case 8:

upMonthDaycounts=31;

break;

case 9:

upMonthDaycounts=31;

break;

case 10:

upMonthDaycounts=30;

break;

case 11:

upMonthDaycounts=31;

break;

case 12:

upMonthDaycounts=30;

break;

default:

break;

}

switch(date.month) {

case 1:

case 5:

case 7:

case 8:

case 10:

case 12:

case 3:

return 31;

case 2:

upMonthDaycounts=31;

if (date.year%4==0&&date.year!=0){

return 29;

}else{

return 28;

}

case 4:

case 6:

case 9:

case 11:

return 30;

default:

return 31;

}

}

-(int)getMonthWeekday:(CFGregorianDate)date

{

CFTimeZoneRef tz =CFTimeZoneCopyDefault();//获得默认时区

CFGregorianDate month_date;

month_date.year=date.year;

month_date.month=date.month;

month_date.day=1;

month_date.hour=1;

month_date.minute=0;

month_date.second=1;

return(int)CFAbsoluteTimeGetDayOfWeek(CFGregorianDateGetAbsoluteTime(month_date, tz),tz);

}

-(void)movePrevOrNextMonth:(int)isPrev

{

intwidth=calendarWidth;

intposX;

if(isPrev==1) {

posX=width;

}else{

posX=-width;

}

UIImage *viewImage;

UIGraphicsBeginImageContext(self.bounds.size);

[self.layerrenderInContext:UIGraphicsGetCurrentContext()];

viewImage=UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

if(viewImageView==nil){

viewImageView=[[UIImageViewalloc]initWithImage:viewImage];

viewImageView.center=self.center;

[[self superview]addSubview:viewImageView];

}else{

viewImageView.image=viewImage;

}

viewImageView.hidden=NO;

viewImageView.transform=CGAffineTransformMakeTranslation(0,0);

[selfsetHidden:YES];

[selfsetNeedsDisplay];

self.transform=CGAffineTransformMakeTranslation(posX,0);

self.hidden=NO;

for(UIButton *button in self.subviews) {

if( [buttonisKindOfClass:[UIButton class]] )

{

[buttonremoveFromSuperview];

}

}

for(UILabel *button in self.subviews) {

if( [buttonisKindOfClass:[UILabel class]] )

{

[buttonremoveFromSuperview];

}

}

[selfdrawDateWords];

[selfdrawTopWeekDay];

[UIViewbeginAnimations:nilcontext:nil];

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];

[UIView setAnimationDuration:0.5];

self.transform=CGAffineTransformMakeTranslation(0,0);

viewImageView.transform=CGAffineTransformMakeTranslation(-posX,0);

[UIViewcommitAnimations];

}

-(void)movePrevMonth

{

if(currentMonthDate.month>1){

currentMonthDate.month-=1;

}else{

currentMonthDate.month=12;

currentMonthDate.year-=1;

}

[selfmovePrevOrNextMonth:0];

}

-(void)moveNextMonth

{

if(currentMonthDate.month<12){

currentMonthDate.month+=1;

}else{

currentMonthDate.month=1;

currentMonthDate.year+=1;

}

[selfmovePrevOrNextMonth:1];

}

-(void)drawRect:(CGRect)rect

{

[selfdrawGirdLines];

}

-(void)changeButtonColor:(UIButton*)button

{

}

-(void)dateButtonClicked:(UIButton*)buttontag

{

// NSString*clickedDay=[[NSString alloc]initWithFormat:@"%@",buttontag.tag];

if(currentMonthDate.month<10) {

selectDay=[[NSStringalloc]initWithFormat:@"%i-0%i-%i",currentMonthDate.year,currentMonthDate.month,buttontag.tag];

}else {

selectDay=[[NSStringalloc]initWithFormat:@"%i-%i-%i",currentMonthDate.year,currentMonthDate.month,buttontag.tag];

}

if(isContinuousClick){

if(buttontag.alpha==1.0) {

if (![selectDayisEqualToString: saveMonthDate]) {

[buttontagsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];

buttontag.backgroundColor=[UIColor colorWithRed:0.29 green:0.63 blue:0.91 alpha:1.0];

buttontag.alpha=0.9;

}

}else{

[buttontagsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

buttontag.backgroundColor =[UIColor colorWithRed:0.847green:0.847 blue:0.847 alpha:1.0];

buttontag.alpha=1.0;

}

}else{

for (UIButton*button in self.subviews) {

if ([buttonisKindOfClass:[UIButton class]]) {

if(button.alpha!=1.0&&button.tag>0){

[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateNormal];

button.backgroundColor=[UIColorcolorWithRed:0.847green:0.847 blue:0.847 alpha:1.0];

button.alpha=1.0;

}

}

}

if(buttontag.tag!=saveTodaytag) {

[buttontagsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];

buttontag.backgroundColor=[UIColor colorWithRed:0.29 green:0.63 blue:0.91 alpha:1.0];

buttontag.alpha=0.9;

}

}

[delegateclickedCanlendarButton];

[selectDay release];

}

-(void)drawGirdLines{

float headHeight=calendarHeight/5;

floatitemHeight=40;

CGContextRefctx=UIGraphicsGetCurrentContext();

intwidth=calendarWidth;

introw_Count;

if(([selfgetDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate])%7==0){

row_Count=([selfgetDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate]%7)/7;

}else{

row_Count=([selfgetDayCountOfaMonth:currentMonthDate]+[selfgetMonthWeekday:currentMonthDate]%7)/7+1;

}

ints_width=width/7;

inttabHeight=row_Count*itemHeight+headHeight;

CGContextSetGrayStrokeColor(ctx,0,1);

CGContextMoveToPoint   (ctx,0,headHeight);

CGContextAddLineToPoint   (ctx,0,tabHeight);

CGContextStrokePath       (ctx);

CGContextMoveToPoint   (ctx,width,headHeight);

CGContextAddLineToPoint  (ctx,width,tabHeight);

CGContextStrokePath       (ctx);

for(inti=1;i<8;i++){

CGContextSetGrayStrokeColor(ctx,1,1);

CGContextMoveToPoint(ctx, i*s_width-1,headHeight);

CGContextAddLineToPoint( ctx,i*s_width-1,tabHeight);

CGContextStrokePath(ctx);

CGContextSetGrayStrokeColor(ctx,0.3,1);

CGContextMoveToPoint(ctx, i*s_width+2,headHeight);

CGContextAddLineToPoint( ctx,i*s_width+2,tabHeight);

CGContextStrokePath(ctx);

}

for(inti=0;i<row_Count+1;i++){

CGContextSetGrayStrokeColor(ctx,1,1);

CGContextMoveToPoint(ctx, 0,i*itemHeight+headHeight+3);

CGContextAddLineToPoint( ctx,width,i*itemHeight+headHeight+3);

CGContextStrokePath(ctx);

CGContextSetGrayStrokeColor(ctx,0.3,1);

CGContextMoveToPoint(ctx, 0,i*itemHeight+headHeight);

CGContextAddLineToPoint( ctx,width,i*itemHeight+headHeight);

CGContextStrokePath(ctx);

}

}

-(void)dealloc

{

[saveMonthDaterelease];

[superdealloc];

}

@end

http://blog.sina.com.cn/s/blog_796ffec50100tmah.html

循环滚动UIScrollView(有点击事件处理)

1.创建一个继承UIView的名为CycleScrollView的类(.h和.m文件)

2.将下面代码替换原默认代码

3.在你的类里面实例化一个CycleScrollView类的对象并用

- (id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)direction pictures: (NSArray*)pictureArray

进行初始化

参数介绍:

frame页面的位置和大小

direction滚动的方向,0垂直滚动,1水平滚动

pictureArray 滚动的图片数组

比如:

-(void)viewDidLoad

{

[superviewDidLoad];

NSArray*imagesArray=[[NSArray alloc] initWithObjects: [UIImage imageNamed:@"test1.jpg"],[UIImageimageNamed:@"test2.jpg"],[UIImageimageNamed:@"test3.jpg"],nil];

CycleScrollView*cycle=[[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)cycleDirection:0 pictures:imagesArray];

cycle.delegate=self;

[self.viewaddSubview:cycle];

[imagesArrayrelease];

[cyclerelease];

}

//

.h文件

#import <UIKit/UIKit.h>

//枚举,用来判断滚动方向

typedef  enum_CycleDirection

{

PortaitDirection,//纵向滚动

LandscapeDirection//横向滚动

} CycleDirection;

@protocol CycleScrollViewDelegate

-(void)pageViewClicked:(NSInteger)pageIndex;

@end

@interface CycleScrollView :UIView <UIScrollViewDelegate>{

CycleDirectionscrollDirection;    // scrollView滚动的方向

UIScrollView*scrollView;

NSArray*imagesArray;   // 存放所有需要滚动的图片

NSMutableArray*curImages; //存放当前滚动的三张图片

inttotalPageCount;//图片的总张数

intcurPageIndex;//当前图片的索引

CGRectscrollFrame;

id<CycleScrollViewDelegate> delegate;

}

@property (nonatomic,assign)id<CycleScrollViewDelegate> delegate;

- (NSArray*)getDisplayImagesWithPageindex;

- (int)validPageValue:(NSInteger)value;

- (void) refreshScrollView;

- (id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)direction pictures:(NSArray*)pictureArray;

-(void)ButtonClicked;

@end

//

//

.m文件

#import"CycleScrollView.h"

@implementation CycleScrollView

@synthesize delegate;

- (id)initWithFrame:(CGRect)framecycleDirection:(CycleDirection)direction pictures:(NSArray*)pictureArray

{

self =[super initWithFrame:frame];

if (self){

scrollFrame=frame;

scrollDirection=direction;

curImages=[[NSMutableArrayalloc] init];

imagesArray=[[NSArray  alloc]initWithArray:pictureArray];

totalPageCount=[imagesArraycount];

curPageIndex=1;//当前显示的是图片数组里的第一张图片

scrollView=[[UIScrollViewalloc] initWithFrame:frame];

scrollView.backgroundColor=[UIColorblueColor];

scrollView.showsVerticalScrollIndicator=NO;

scrollView.showsHorizontalScrollIndicator=NO;

scrollView.pagingEnabled=YES;

scrollView.delegate=self;

if(scrollDirection == PortaitDirection)

{//在竖直方向滚动

scrollView.contentSize=CGSizeMake(scrollView.frame.size.width,scrollView.frame.size.height*3);

}

if(scrollDirection==LandscapeDirection)

{//在水平方向滚动

scrollView.contentSize=CGSizeMake(scrollView.frame.size.width*3,scrollView.frame.size.height);

}

[self  addSubview:scrollView];

[selfrefreshScrollView];

}

returnself;

}

- (void) refreshScrollView

{

NSArray*subViews=[scrollView subviews];

if([subViews count]>0) {

[subViewsmakeObjectsPerformSelector:@selector(removeFromSuperview)];

}

[selfgetDisplayImagesWithPageindex];

for (inti = 0 ; i < 3;  i++) {

UIButton  *imageButton=[[UIButtonalloc] init];

//        UIButton  *imageButton=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

[imageButtonsetImage:[curImages objectAtIndex:i] forState:UIControlStateNormal];

[imageButtonaddTarget:self action:@selector(ButtonClicked)forControlEvents:UIControlEventTouchUpInside];

if(scrollDirection==PortaitDirection){

imageButton.frame=CGRectOffset(CGRectMake(0,0, 320, 480), 0, scrollFrame.size.height*i);

[scrollViewsetContentOffset:CGPointMake(0, scrollFrame.size.height)];

}

if(scrollDirection==LandscapeDirection){ //水平滚动

imageButton.frame=CGRectOffset(CGRectMake(0,0, 320, 480), scrollFrame.size.width*i, 0);

[scrollViewsetContentOffset:CGPointMake(scrollFrame.size.width, 0)];

}

[scrollViewaddSubview:imageButton];

[imageButtonrelease];

}

}

- (NSArray*)getDisplayImagesWithPageindex

{

intpre=[self validPageValue:curPageIndex-1];

intlast=[self validPageValue:curPageIndex+1];

if([curImagescount]!=0)

[curImagesremoveAllObjects];

[curImagesaddObject:[imagesArray objectAtIndex:pre-1]];

[curImagesaddObject:[imagesArray objectAtIndex:curPageIndex-1]];

[curImagesaddObject:[imagesArray objectAtIndex:last-1]];

returncurImages;

}

- (int)validPageValue:(NSInteger)value

{

if(value==0)

{

value=totalPageCount;    //value=1为第一张,value=0为前面一张

}

if(value==totalPageCount+1) {

value=1;

}

returnvalue;

}

-(void)scrollViewDidScroll:(UIScrollView*)crollView

{

intx=crollView.contentOffset.x;

inty=crollView.contentOffset.y;

if(scrollDirection==LandscapeDirection)//水平滚动

{

if(x>=2*scrollFrame.size.width)//往下翻一张

{

curPageIndex=[selfvalidPageValue:curPageIndex+1];

[selfrefreshScrollView];

}

if(x<=0)

{

curPageIndex=[selfvalidPageValue:curPageIndex-1];

[selfrefreshScrollView];

}

}

//竖直滚动

if(scrollDirection==PortaitDirection){

if(y>=2*scrollFrame.size.height)

{

curPageIndex=[selfvalidPageValue:curPageIndex+1];

[selfrefreshScrollView];

}

if(y<=0) {

curPageIndex=[selfvalidPageValue:curPageIndex-1];

[selfrefreshScrollView];

}

}

}

-(void)ButtonClicked

{

[delegatepageViewClicked:curPageIndex];

}

- (void)dealloc

{

[imagesArrayrelease]

[curImagesrelease]

[superdealloc];

}

@end

一些iOS高效开源类库

因为iOSSDK相对比较底层,所以开发者就得受累多做一些体力活。不过幸运的是,有很多第三方的类库可以用来简化很多不必要的工作。整理了一下在本人学习过程中用到的一些比较有用Objective-C开源类库,既是做一个总结,同时也希望通过这些分享,能提高各位的开发效率。

KissXml——xml解析库

相关教程:http://www.iteye.com/topic/625849

http://sencho.blog.163.com/blog/static/83056228201151743110540/

很方便的一个xml解析器,支持Xpath查询。

skpsmtpmessage——Quick SMTP邮件发送

svn checkout http://skpsmtpmessage.googlecode.com/svn/trunk/ skpsmtpmessage-read-only

github:      git clone https://github.com/kailoa/iphone-smtp.git

相关教程:http://disanji.net/2011/01/28/skpsmtpmessage-open-source-framework/

skpsmtpmessage 是由Skorpiostech, Inc.为我们带来的一个SMTP协议的开源实现,使用Objective-c实现,iOS系统的项目可以直接调用。

jsonframework——JSON支持

相关教程:http://blog.csdn.net/xiaoguan2008/article/details/6732683

它是一个开源框架,基于BSD协议发布。由于json-framework是开放源代码的,当你需要使用它时你只需将json的源代码加入到你的工程中。

ASIHttpRequest——HTTP Network库

ASIHttpRequest库极大的简化了网络通 信,提供更先进的工具,例如文件上传工具,重定向处理工具、验证工具、等等。

MBProgressHUD——进展指示符库

苹果的应用程序一般都会用一种优雅的,半透明的进度显示效果,不过这个API是不公开的,因此你要是用了,很可能被清除出AppStore。而MBProgressHUD提供了一个替代方案,而且在用户角度上,实现的效果根本看不出和官方程序有什么差别。同时还提供了其他附加功能,比如虚拟进展 指示符,以及完成提示信息。整合到项目里也很容易,这里不细谈了。

zxing——二维码扫描库

支持条形码/二维码扫描的图形处理库,这是一个java库,在android上的功能比较完整。同时该库也支持ios,但只能支持二位条形码的扫描。

kal——iPhone日历控件

一个类似于ios系统默认日历开源日历库,支持添加事件,自定义日历样式等功能。

Facebook iOS SDK——Facebook API类库

大体来讲就是iPhone上的Facebook login,完全支持Facebook Graph API和the older REST api。

shareKit——分享库

相关demo:http://www.cocoachina.com/bbs/read.php?tid-71760.html

分享到开心,豆瓣,腾讯,新浪微博的api所用到的强大的分享库。

SDWebImage——简化网络图片处理

用SDWebImage调用网站上的图片,跟本地调用内置在应用包里的图片一样简单。操作也很简单。

GDataclient——iPhone上所有Google相关服务的类库

名字就说明一切了。跟Google相关的,值得一提的是,这个项目很开放。有很多示例程序供下载。

CorePlot——2D图形绘图仪

CorePlot有很多解决方案将你的数据可视。同时也会提供各种迷人的图形效果,比如棒状图、饼状图、线状图等等,在他们网站上也提供了大量的范例图形,很多股票价格应用,游戏分数,个人财务管理都在用。

Three20——类似于Facebook的优秀的UI库

Three20类库是Facebook自己做的,大而全是他最大的特色。把他整合到已有的项目中可能得费点周折,不过如果一开始你就用上了Three20,尤其是牵扯到很多web相关的项目的时候,你就能深刻体会到神马叫给力了。

FMDatabase——SQLite的Objective-C封装

是SQLite的C API對初學者來說實在太麻煩太瑣碎,難度太高。FMDB說穿了其實只是把C API包裝成簡單易用的Objective-C类。對于SQLite初學者來說,大大減低了上手的難度。有了FMDB,寫程式時只要專心在SQLite的語法上,而不用去理那堆有看沒有懂的C API,實在是件快樂的事情。

读取iOS代理设置的代码

公司网络很多都是有代理设置的,如果设备通过wifi上网,就要过公司网络代码。

于是想到一个问题:如何读取iOS设备的代理设置?

用过ASIHTTPRequest这个开源网络库,它可以读取代理设置,于是我在源码中发现读取代理设置的方法,我已把代码提取出来:

NSDictionary*proxySettings = NSMakeCollectable([(NSDictionary*)CFNetworkCopySystemProxySettings() autorelease]);

NSArray *proxies =NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[NSURLURLWithString:@"http://www.google.com"],(CFDictionaryRef)proxySettings) autorelease]);

NSDictionary*settings = [proxies objectAtIndex:0];

NSLog(@"host=%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);

NSLog(@"port=%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);

NSLog(@"type=%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);

需要CFNetwork.framework

新浪微博iOS版SDK框架学习笔记

本文为论坛会员3h2om分享,对新浪微博iOS版SDK-“宝玉XP”框架进行研究所写的学习笔记,非常详细和精彩。

在学习的过程中,对新浪微博iOS版SDK-“宝玉XP”框架进行了学习(下载地址:https://github.com/JimLiu/WeiboSDK),在没有获得相应的说明文档前提下,要理解其中的内幕对于初涉OPEN API的新人来说不算是件易事,为了满足一窥究竟的一惯心理,我在对其源代码进行一番抽丝剥茧式的跟踪后,基本上搞懂了框架内各类之间的调用关系,初略地理解了各类的大概用途,也对OAuth 认证机会有了进一步的认识。充分理解该框架后将对于开发基于HTTP协议的类似项目有一定的参考作用。现将我的这种“理解”简要地进行整理,愿能对学习并想了解该SDK的人有所帮助。

一、组成和关系

该框架除了由大量的诸如数据连接、数据模型等基础类支撑外,其主要的功能由 RootViewControllerComposeViewController、OAuthcontroller、OAuthEngine URLConnection、WeiboClient 6个类完成,RootViewController是整个框架的视图控制器,它作为应用程序委托中的UINavigationController类型的输出口,控制该系统的主视图以呈现给用户。ComposeViewController类是作为RootViewController类的组成部分存在的,用以控制写微博时所呈现出的发送视图。OAuthcontrller用以控制完成OAuth认证机制所需要的视图。类OAuthEngine、URLConnection、WeiboClient为服务类,为各视图控制类提供服务,类OAuthEngine为完成OAuth方式认证提供了支持,通过该方法完成授权和认证过程,URLConncetion和WeiboClient建立网络连接,实现新浪提供的OPEN API功能,设置并完成HTTP请求以发送和接受数据。

二、各类简单说明

1、RootViewController类

该类是整个系统的视图控制类,是系统与外面交互的入口,也是系统的运行的驱动点,它关联了OAuthEngine等服务类,在该类通过调用其他各服务类提供的功能,完成从用户的登录授权认证到把微博客。在viewDidLoad方法中,完成了对用于保存微博列表的NSMutableArray类的status的初如化。接着在viewDidAppear方法中,用服务方提供的三个URL和应用程序在新浪方获取的Key和Secret完成其成员OAuthEngine类型的_engine的初始化工作,为OAuth认证提供了准备。在此之类,就调用自身loadTimeline方法,来完成包括OAuth认证、请求数据等一系列动作,从此,系统运行的万里长征正式踏上征程。

2、ComposeViewController类

该类所控制的视图是RootViewController类所控制的视图的组成一部分,当用户点击主视图上面导航栏中的发送按钮,该类所控制的视图将呈现出来,主要用于发送微博。Draft类描述发送微博时的附件信息,newTweet方法的主要作用是初始化draft,为发送新的微博上传相关附件提供对应的对象,send方法用于调用的OPENGAPI完成发送这一动作,insert方法在发送微博时插入附件时被调用。

3、OAuthController类该类主要用于调用OAuthEngine类的服务来完成OAuth认证机制中的认证工作的三步认证,它由RootViewController类中的loodTimeline方法调用。该类中的_webView成员是用来显示用户授权界面的UIVebView控件,因此就实现了UIWebViewDelegate委托,用委托中相应的方法协调完成认证过程。该控件的URLRequest属性被设置为三步认证中的第二个URL,用于获取用户授权的RequestToken。

4、OAuthEngine类该类是OAuth认证实现的核心类,为其他类提供认证服务。调用requestRequestToken将获取到经过授权的获取用户授权的Request Token,调用requestAccessToken将用授权的Request Token换取Access Token。

5、URLConnection和WeiboClient类WeiboClient是URLConnection的子类,WeiboClient实现了OPEN API方法,设置并完成HTTP请求以发送和接受数据,并用指定的action来处理通过的HTTP请求得到数据。

二、进入用户授权界面的步骤

系统运行后,经过RootViewController类的viewDidApper事件方法,调用其lodadTimeline方法完成OAuth认证机制的第一步(获取未授权的RequestToken),之后进入到OAuthController类的loadView方法,该方法中通过语句:“*request= _engine.authorizeURLRequest; [_webView loadRequest: request];”完成认证机制中第二步,接着进入到webViewDidFinshg

事件方法,进入到授权界面。具体细节比较复杂,见下面的(进入授权界面的时序图),由于没有专门的UML工具,加之涉及到的对象较多,时序图没有列出所有的对象和细节。在进入RootViewController的viewDidAppear事件方法中,判断该类中的_engine是否已经存在,如果没有就对其初始化,接着调用“[self performSelector:@selector(loadTimeline)withObject:nil afterDelay:0.0]; ”进入到loadTimeline方法中。loadTimeline方法首先用本类中的实例成员_engine作为参数,着手构建OAuthController对象,下一步就判断刚刚构建的动作是否真的构建了对象,如果对象存在,就立即转入到刚刚构建OAuthController类对象所对应的视图,即进入到授权界面,以供用户进行授权。如果不存在OAuthController对象,就说明已经完成了认证,不用进入到授权界面,直接调用loadData加载与授权用户相关的微博信息后,进入到RootViewController对应视图即可。其中创建OAuthController对象是关键,在其中进行了判断,如果已经授权了或者cache中还保存着相应的cooke的话,就退出,否则就用_engine为参数,调用OAuthController的初始化方法,初始化后又判断_engine.OAuthSetup 的值,如果为NO则表示还没有进行过认证(若为YES则表示已经完成了认证步中的第一步),于是就调用¬¬¬¬_engine requestRequestToken来完成认证的第一步操作。OAuthEngine类中requestRequestToken方法的调用过程:该方法是一中间方法,起到过渡作用,它只是调用 requestURL: token:onSuccess: onFai:方法,后一个方法用指定的URL和两个方法SEL作为参数,其中两个SEL分别用于当该HTTP请求成功或失败返回时对应的处理方法。它分别指定为setRequestToken和outhTicketFailed方法。

OAuthEngine类中的requestURL:token:onSuccess:onFail方法又用给定的URL和token构建了OAMutableURLRequest对象,然后构建OADataFetcher对象,并把它来提取基于OAMutableURLRequest网络连接的数据(调用onSucess:和onFail方法)。如果成功,就调用上面传过来的OAuthEngine类中setRequestToken方法处理认证第一步的返回数据。setRequestToken只是用得到的数据填充用OAuthEngine类中的_requestToken。

至此,已经完成了构建OAuthController对象,并工作完成了OAuth认证中的第一步了。接着,程序一路回退,回退至loadTimeline

方法中:

UIViewController*controller = [OAuthController controllerToEnterCredentialsWithEngine: _enginedelegate:self]//通过以上的过程,该句已经执行完毕

if(controller)//第一次进入时总需要认证,总会构建controller,所以为为真值

[selfpresentModalViewContrllor: controller animated:YES];//

else

[self loadData];由于presentModalViewContrllor是异步方法,调用后,loadTimeline就当即结束了。经过几番系统 的“原子操作后”,进入到OAuthController类中的loadView 事件方法中,在该事件方法中,将完成OAuth认证机制中的第二步过程。该方法对即将出现的授权界面中的一些UI进行了初始化设置后,调用:

NSURLRequest*request = _engine.authorizeURLRequest;

[_webViewloadRequest:request];

在OAuthEngine类的authorizeURLRequest方法中,首先判断_requestToke.key是否为空(由于我在第一步的认证过程上,已经设置好了),若不为空,则用authorizeURL和_requestToken等为参数,构建OAMutableURLRequest对象,并基于此设置好相关的HTTP请求,并返回供_webView加载,loadView结束后再进入_webViewDidFinishLoad事件方法。

至此,授权界面已经出现,以供用户对其授权,界面如下:

此过程的详细调用情况见下图:

接上:进入授权界面的时序图

三、用户授权后并进入到微博主界面的调用关系

当用户在授权界面上填写好帐号和密码后,点击“授权”后,触发OAuthController类的webViewStartLoadWithRequest事件和webViewDidFinishLoad方法,在webViewDidFinishLoad中调用gotPin方法得到AccessToken完成OAuth认证机制的最后一步。之后RootViewController类中的viewDidAppear事件方法被触发,在该方法中,调用loadData方法,完成数据的加载工作,然后就显示了微博的主列表界面。

具体细节比较复杂,见下面的(进入授权界面的时序图),由于没有专门的UML工具,加之涉及到的对象较多,时序图没有列出所有的对象和细节。该时序图仅描述用户授权过程(即OAuth认证的最后步),没有描述认证后其中加载数据的详细过程,详细过程见方法调用图。

几个重要方法:

RootViewController类中loadTimeline方法:该方法是本框架中的一个主要中转方法,此方法调用OAuthController类的controllerToEnterCredentialsWithEng

ine完成认证中的前两步操作,调用loadData方法完成认证的第三步和加载数据过程。

OAuthEngine类中的requestRequestToken方法用来完成认证第步的请求,setRequestToken方法用来处理接收数据,并设置好_requestToken;requestAccessToken方法用来完成认证第三步,setAccessToken方法用来处理上步接收的数据,并设置_accessToken

从而完成整个认证操作。OAuthController类中的locateAuthPinInW

ebView方法用来从返回的HTTP请求中获取PIN码,即获取用授权的Request Token,完成认证的第二步,用此来作为第三步的参数。

RootViewController类中的timelineDidReceiveForComment方法用来处理接收从HTTP请求返回中的数据,在此方法中实现微博的数据的反序列化工作。

四、几点发现

1、OAuthController类中的webViewDiFinishLoad事件方法中通过调用: _delegate OAuthController:self authenticatiedWit

ntroller:authenticatedWithUserName:_engine.username方法间接地又调用了一次loadTimeline和loadData 方法生成WeiboCleint

对象并进行认证和加载数据操作,但由于WeiboClient对象是自动销毁后,程序立即进入到了RootViewController类的viewDidApper事件方法,在这个方法中又调用loadTimeline,以至于上面的操作是多余的,等于在进行了两次认证(第二步和第三步)和加载数据操作。

2.关于OAuthController类中的webView:shouldStartLoadWit

hRequest事件方法(视图类的相关事件方法也一样)连续被调用多次问题。这是一个很有趣的问题,至今我没有发现什么原因。比如说要转到(presentModalViewController:)一个视图(该视图实现了UIWebViewDelegate委托),该视图控制器中实现了viewDidLoad和loadView事件方法,如果在这些方法中没有调用其父类的对应方法,则被转到的视图控制器中的这两个方法会连接地被调用,我一次试验是连续地被调用了11次?但如果加上 super viewDidLoad 的话只正常地被调用1次。至于是什么原因,我至今未懂。

获得通讯录中联系人的所有属性

获得通讯录中联系人的所有属性 ,看代码: ABAddressBookRef addressBook = ABAddressBookCreate();CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(addressBook);

获得通讯录中联系人的所有属性 ,看代码:

ABAddressBookRef addressBook = ABAddressBookCreate();

CFArrayRefresults = ABAddressBookCopyArrayOfAllPeople(addressBook);

for(inti = 0; i < CFArrayGetCount(results); i++)

{

ABRecordRefperson = CFArrayGetValueAtIndex(results, i);

//读取firstname

NSString*personName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);

if(personName!= nil)

textView.text= [textView.text stringByAppendingFormat:@"\n姓名:%@\n",personName];

//读取lastname

NSString*lastname = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);

if(lastname!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",lastname];

//读取middlename

NSString*middlename = (NSString*)ABRecordCopyValue(person,kABPersonMiddleNameProperty);

if(middlename!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",middlename];

//读取prefix前缀

NSString*prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);

if(prefix!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",prefix];

//读取suffix后缀

NSString*suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);

if(suffix!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",suffix];

//读取nickname呢称

NSString*nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);

if(nickname!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",nickname];

//读取firstname拼音音标

NSString*firstnamePhonetic = (NSString*)ABRecordCopyValue(person,kABPersonFirstNamePhoneticProperty);

if(firstnamePhonetic!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",firstnamePhonetic];

//读取lastname拼音音标

NSString*lastnamePhonetic = (NSString*)ABRecordCopyValue(person,kABPersonLastNamePhoneticProperty);

if(lastnamePhonetic!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",lastnamePhonetic];

//读取middlename拼音音标

NSString*middlenamePhonetic = (NSString*)ABRecordCopyValue(person,kABPersonMiddleNamePhoneticProperty);

if(middlenamePhonetic!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",middlenamePhonetic];

//读取organization公司

NSString*organization = (NSString*)ABRecordCopyValue(person,kABPersonOrganizationProperty);

if(organization!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",organization];

//读取jobtitle工作

NSString*jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);

if(jobtitle!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",jobtitle];

//读取department部门

NSString*department = (NSString*)ABRecordCopyValue(person,kABPersonDepartmentProperty);

if(department!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",department];

//读取birthday生日

NSDate*birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);

if(birthday!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",birthday];

//读取note备忘录

NSString*note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);

if(note!= nil)

textView.text= [textView.text stringByAppendingFormat:@"%@\n",note];

//第一次添加该条记录的时间

NSString*firstknow = (NSString*)ABRecordCopyValue(person,kABPersonCreationDateProperty);

NSLog(@"第一次添加该条记录的时间%@\n",firstknow);

//最后一次修改該条记录的时间

NSString*lastknow = (NSString*)ABRecordCopyValue(person,kABPersonModificationDateProperty);

NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

//获取email多值

ABMultiValueRefemail = ABRecordCopyValue(person, kABPersonEmailProperty);

intemailcount = ABMultiValueGetCount(email);

for(int x = 0; x < emailcount; x++)

{

//获取email Label

NSString*emailLabel =(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email,x));

//获取email值

NSString*emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x);

textView.text= [textView.textstringByAppendingFormat:@"%@:%@\n",emailLabel,emailContent];

}

//读取地址多值

ABMultiValueRefaddress = ABRecordCopyValue(person, kABPersonAddressProperty);

intcount = ABMultiValueGetCount(address);

for(intj = 0; j < count; j++)

{

//获取地址Label

NSString*addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j);

textView.text= [textView.text stringByAppendingFormat:@"%@\n",addressLabel];

//获取該label下的地址6属性

NSDictionary*personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address,j);

NSString*country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];

if(country!= nil)

textView.text= [textView.text stringByAppendingFormat:@"国家:%@\n",country];

NSString*city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];

if(city!= nil)

textView.text= [textView.text stringByAppendingFormat:@"城市:%@\n",city];

NSString*state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];

if(state!= nil)

textView.text= [textView.text stringByAppendingFormat:@"省:%@\n",state];

NSString*street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];

if(street!= nil)

textView.text= [textView.text stringByAppendingFormat:@"街道:%@\n",street];

NSString*zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];

if(zip!= nil)

textView.text= [textView.text stringByAppendingFormat:@"邮编:%@\n",zip];

NSString*coutntrycode = [personaddress valueForKey:(NSString*)kABPersonAddressCountryCodeKey];

if(coutntrycode!= nil)

textView.text= [textView.text stringByAppendingFormat:@"国家编号:%@\n",coutntrycode];

}

//获取dates多值

ABMultiValueRefdates = ABRecordCopyValue(person, kABPersonDateProperty);

intdatescount = ABMultiValueGetCount(dates);

for(int y = 0; y < datescount; y++)

{

//获取dates Label

NSString*datesLabel =(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates,y));

//获取dates值

NSString*datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y);

textView.text= [textView.text stringByAppendingFormat:@"%@:%@\n",datesLabel,datesContent];

}

//获取kind值

CFNumberRefrecordType = ABRecordCopyValue(person, kABPersonKindProperty);

if(recordType == kABPersonKindOrganization) {

//it's a company

NSLog(@"it'sa company\n");

}else {

//it's a person, resource, or room

NSLog(@"it'sa person, resource, or room\n");

}

//获取IM多值

ABMultiValueRefinstantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);

for(int l = 1; l < ABMultiValueGetCount(instantMessage); l++)

{

//获取IM Label

NSString*instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage,l);

textView.text= [textView.textstringByAppendingFormat:@"%@\n",instantMessageLabel];

//获取該label下的2属性

NSDictionary*instantMessageContent =(NSDictionary*)ABMultiValueCopyValueAtIndex(instantMessage, l);

NSString*username = [instantMessageContent valueForKey:(NSString*)kABPersonInstantMessageUsernameKey];

if(username!= nil)

textView.text= [textView.text stringByAppendingFormat:@"username:%@\n",username];

NSString* service =[instantMessageContent valueForKey:(NSString*)kABPersonInstantMessageServiceKey];

if(service!= nil)

textView.text= [textView.text stringByAppendingFormat:@"service:%@\n",service];

}

//读取电话多值

ABMultiValueRef phone =ABRecordCopyValue(person, kABPersonPhoneProperty);

for(int k = 0; k<ABMultiValueGetCount(phone); k++)

{

//获取电话Label

NSString* personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone,k));

//获取該Label下的电话值

NSString* personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);

textView.text= [textView.text stringByAppendingFormat:@"%@:%@\n",personPhoneLabel,personPhone];

}

//获取URL多值

ABMultiValueRefurl = ABRecordCopyValue(person, kABPersonURLProperty);

for(int m = 0; m < ABMultiValueGetCount(url); m++)

{

//获取电话Label

NSString* urlLabel =(NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url,m));

//获取該Label下的电话值

NSString* urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m);

textView.text= [textView.textstringByAppendingFormat:@"%@:%@\n",urlLabel,urlContent];

}

//读取照片

NSData*image = (NSData*)ABPersonCopyImageData(person);

UIImageView*myImage = [[UIImageView alloc] initWithFrame:CGRectMake(200, 0, 50, 50)];

[myImagesetImage:[UIImage imageWithData:image]];

myImage.opaque= YES;

[textViewaddSubview:myImage];

}

CFRelease(results);

CFRelease(addressBook);

iPhone开发中经常用到的控件尺寸大集合

Element

Size (in points)

Window (including status bar)

320 x 480 pts

Status Bar

(How to hide the status bar)

20 pts

View inside window

(visible status bar)

320 x 460

Navigation Bar

44 pts

Nav Bar Image /

Toolbar Image

up to 20 x 20 pts (transparent PNG)

Tab Bar

49 pts

Tab Bar Icon

up to 30 x 30 pts (transparent PNGs)

Text Field

31 pts

Height of a view inside

a navigation bar

416 pts

Height of a view inside

a tab bar

411 pts

Height of a view inside

a navbar and a tab bar

367 pts

Portrait Keyboard height

216 pts

Landscape Keyboard height

140 pts

Points vs. Pixels

The iPhone 4 introduced a high resolution display with twice the pixels of previous iPhones. However you don't have to modify your code to support high-res displays; the coordinate system goes by points rather than pixels, and the dimensions in points of the screen and all UI elements remain the same.

iOS 4 supports high resolution displays (like the iPhone 4 display) via the scale property on UIScreen, UIView, UIImage, and CALayer classes. If the object is displaying high-res content, its scale property is set to 2.0. Otherwise it defaults to 1.0.

All you need to do to support high-res displays is to provide @2x versions of the images in your project. See the checklist for updating to iOS4 or Apple documentation for Supporting High Resolution Screens for more info.

Adjusting Sizes

Click here to see how to adjust View Frames and Bounds.

Additional References

35.         Apple Documentation: Points vs. PixelsApple Documentation: UIBarButtonItem Class Reference says "Typically, the size of a toolbar and navigation bar image is 20 x 20 points."Apple Documentation: UITabBarItem Class Reference says "The size of an tab bar image is typically 30 x 30 points."

 

图片:iPhone开发中经常用到的控件尺寸大集合.png

一个完整的SQLite的应用DEMO

自己写了一个iphone应用sqlite的DEMO;

涉及到添加,查询和事务管理

关键代码

if (sqlite3_open([[self databasePath] UTF8String],&database) != SQLITE_OK) {

sqlite3_close(database);

NSAssert(0,@"open database faild!");

}

char *erroMsg;

NSString *createSQL= [NSString stringWithFormat:@"CREATE TABLEIF NOT EXISTS %@(ROW INTEGER PRIMARY KEY,NAME TEXT,AGE TEXT,SEX TEXT)",TableName];

if (sqlite3_exec(database, [createSQL UTF8String], NULLNULL, &erroMsg) != SQLITE_OK) {

sqlite3_close(database);

NSAssert1(0,@"create table %@ faild",TableName);

NSAssert1(0,@"the error is %s",erroMsg);

}

NSString *insertUser = [NSString stringWithFormat:@"INSERT INTO %@(NAME,AGE,SEX)VALUES('%@','%@','%@')",TableName,new_user.name,new_user.age,new_user.sex];

NSLog(@"%@",insertUser);

if (sqlite3_exec (database, [insertUser UTF8String], NULLNULL, &erroMsg) != SQLITE_OK)

{

NSAssert1(0, @"Error updating tables: %s", erroMsg);

}

User *user = [[User allocinit];

NSString *countSQL= [NSString stringWithFormat:@"SELECTROW,NAME,AGE,SEX FROM UserTable WHERE ROW = %i",id];

sqlite3_stmt *statement;

if (sqlite3_prepare_v2(database, [countSQL UTF8String], -1, &statement, nil) == SQLITE_OK) {

while (sqlite3_step(statement)==SQLITE_ROW) {

user.id =[NSString stringWithFormat:@"%d",sqlite3_column_int(statement,0)];

user.name =[NSString stringWithFormat:@"%s",sqlite3_column_text(statement,1)];

user.age=[NSString stringWithFormat:@"%s",sqlite3_column_text(statement,2)];

user.sex =[NSString stringWithFormat:@"%s",sqlite3_column_text(statement,3)];

}

sqlite3_finalize(statement);

return user;

}

希望对大家有用:SQLiteDEMO

iOSframework 制作教程

我们使用一种变通的方法来制作 iOSframework,废话不多说,上步骤:

1.打开Xcode创建一个“Cocoa TouchStatic Library”工程,并删除现有的target.

2.右键project选择添加NewTarget,在弹出的窗口中找到Cocoa ,在Cocoa右侧窗口中选择“Loadable Bundle”。

注意:到这步的时候不要选择framework,应为framework是MAC OS上的,iOS是不支持的,但是iOS 支持“Loadable Bundle(cfbundle)”

3.target 上右键get Info 在Build  Settings下面设置下面的5项内容:

a.搜索Wrapper Extension,把默认的bundle改成framework.

b.修改Mach-O Type 为Relocatable Object File.

c.关闭Dead Code Stripping ,把勾去掉!

d.关闭Link With Standard Libraries.

e.移除所有关于“AppKit”  和  “Foundation”的参考,删除“Other Linker Flags”的所有值,并删除“GCC_PREFIX_HEADER“的值!

4.在frameworks Info.plist文件中将Bundle OS Type code的值BNDL改为:FMWK,并且在target的 getinfo窗口中的Properties标签栏下也将Type改为FMWK。

5.在工程中添加你的代码。

例如:我们添加一个类

#import<Foundation/Foundation.h>

@interface Help :NSObject {

}

- (void)show;

@end

#import"Help.h"

@implementation Help

- (void)show

{

NSLog(@"framework!!!");

}

@end

6.在target上右键Add---NewBuild Phase---New Copy Headers Build Phase,此时target下面会多出一个灰色的文件夹—CopyHeaders。

7.然后将我们刚才添加的Help类的.h文件从上面拖到下面的Copy Headers中,再在该文件夹上右键—Set Role---Public.

8.从上面将所有要打进framework的.m文件拖到target下的CompileSources文件夹里。

9.编译,如果出错,那就在  Build下面的 将“OtherLinker Flags “设置为 –ObjC 、-all_load、-lxml2,不要写在一起,请一项项添加。

注意:如果编译出现大量的错误,说明你没有删除“AppKit”  和  “Foundation”的参考,

编译后参考:

在build/Debug-iphonesimulator下面出现一个framework文件夹:

使用我们刚才制作的framework

在新的工程中导入framework

我们把刚才制作的kibernet.framework拷贝到新的工程的目录下,选择kibernet.framework文件夹

添加后的效果图

使用framework中的类:

导入头文件

ViewDid Load中测试一下:

输出结果:

Kibernet.zip

TestFramework.zip

把整个工程做成一个静态库,再集成到别人的工程里。

MapKit学习笔记及源码分享

1、概述

插入MapView,设置Delegate(一般为Controller),Annotations记录兴趣位置点(AnnotationView用来显示兴趣位置点),annotation是可选的,选中的annotation会显示callout,用来显示信息。

2、设置地图显示类型:

mapView.mapType =MKMapTypeStandard;

mapView.mapType =MKMapTypeSatellite;

mapView.mapType =MKMapTypeHybrid;

3、显示用户位置

设置为可以显示用户位置:

mapView.showsUserLocation= YES;

判断用户当前位置是否可见(只读属性):

userLocationVisible

得到用户位置坐标:当userLocationVisible为YES时

CLLocationCoordinate2Dcoords = mapView.userLocation.location.coordinate;

4、坐标范围

MKCoordinateRegion用来设置坐标显示范围。

包括两部分:Center(CLLocationCoordinate2D struct,包括latitude和longitude),坐标中心

和Span(MKCoordinateSpan struct,包括latitudeDelta和longitudeDelta),缩放级别

MKCoordinateRegionviewRegion = MKCoordinateRegionMakeWithDistance(center,2000, 2000);

以上代码创建一个以center为中心,上下各1000米,左右各1000米得区域,但其是一个矩形,不符合MapView的横纵比例

MKCoordinateRegionadjustedRegion = [mapView regionThatFits:viewRegion];

以上代码创建出来一个符合MapView横纵比例的区域

[mapViewsetRegion:adjustedRegion animated:YES];

以上代码为:最终显示该区域

5、Delegate

使用MapView须符合MKMapViewDelegate协议

5.1、地图加载Delegate

当需要从Google服务器取得新地图时

mapViewWillStartLoadingMap:

当成功地取得地图后

mapViewDidFinishLoadingMap:

当取得地图失败后(建议至少要实现此方法)

mapViewDidFailLoadingMap:withError:

5.2、范围变化Delegate

当手势开始(拖拽,放大,缩小,双击)

mapView:regionWillChangeAnimated:

当手势结束(拖拽,放大,缩小,双击)

mapView:regionDidChangeAnimated:

判断坐标是否在MapView显示范围内:

CLLocationDegreesleftDegrees = mapView.region.center.longitude–(mapView.region.span.longitudeDelta / 2.0);

CLLocationDegreesrightDegrees = mapView.region.center.longitude+(mapView.region.span.longitudeDelta / 2.0);

CLLocationDegreesbottomDegrees = mapView.region.center.latitude–(mapView.region.span.latitudeDelta / 2.0);

CLLocationDegreestopDegrees = self.region.center.latitude +(mapView.region.span.latitudeDelta /2.0);

if (leftDegrees >rightDegrees) { // Int'l Date Line in View

leftDegrees = -180.0- leftDegrees;

if (coords.longitude> 0) // coords to West of Date Line

coords.longitude =-180.0 - coords.longitude;

}

If (leftDegrees<= coords.longitude && coords.longitude <= rightDegrees&& bottomDegrees <= coords.latitude && coords.latitude <=topDegrees) {

// 坐标在范围内

}

6、Annotation

Annotation包含两部分:Annotation Object和Annotation View

Annotation Object必须符合协议MKAnnotation,包括两个方法:title和subtitle,分别用于显示注释的标题和子标题。还有coordinate属性,返回CLLocationCoordinate2D,表示Annotation的位置

然后,需使用mapView:viewForAnnotation:方法来返回MKAnnotationView或者MKAnnotationView的子类用来显示Annotation(注意:这里显示的不是选中Annotation后的弹出框)

你可以子类化MKAnnotationView,然后再drawRect:方法里面进行自己的绘制动作(这个方法很蠢)

你完全可以实例化一个MKAnnotationView,然后更改它的image属性,这样很简单。

7、添加移除Annotation

添加一个Annotation

[mapView addAnnotation:annotation];

添加一个Annotation数组

[mapViewaddAnnotations:[NSArray arrayWithObjects:annotation1, annotation2, nil]];

移除一个Annotation

removeAnnotation:

移除一个Annotation数组

removeAnnotations:

移除所有Annotation

[mapViewremoveAnnotations:mapView.annotations];

8、选中Annotation

一次只能有一个Annotation被选中,选中后会出现CallOut(浮动框)

简单的CallOut显示Title和SubTitle,但你也可以自定义一个UIView作为CallOut(与自定义的TableViewCell一样)

可通过代码选中Annotation:

selectAnnotation:animated:

或者取消选择:

deselectAnnotation:animated:

9、显示Annotation

通过mapView:viewForAnnotation:方法显示Annotation,每在MapView中加入一个Annotation,就会调用此方法

示例(与tableView:cellForRowAtIndexPath:很相似)

- (MKAnnotationView*) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {

static NSString*placemarkIdentifier = @"my annotation identifier";

if ([annotationisKindOfClass:[MyAnnotation class]]) {

MKAnnotationView*annotationView = [theMapViewdequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];

if (annotationView== nil) {

annotationView =[[MKAnnotationView alloc] initWithAnnotation:annotationreuseIdentifier:placemarkIdentifier];

annotationView.image= [UIImage imageNamed:@"blood_orange.png"];

}

else

annotationView.annotation= annotation;

returnannotationView;

}

return nil;

}

10、取得真实地址

示例:

初始化MKReverseGeocoder

MKReverseGeocoder*geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinates];

geocoder.delegate =self;

[geocoderstart];

如果无法处理坐标,则调用reverseGeocoder:didFailWithError:方法

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError*)error {

NSLog(@"Errorresolving coordinates: %@", [error localizedDescription]);

geocoder.delegate =nil;

[geocoderautorelease];

}

如果成功,则调用reverseGeocoder:didFindPlacemark:并把信息存储在MKPlacemark 中

didFindPlacemark:(MKPlacemark*)placemark {

NSString*streetAddress = placemark.thoroughfare;

NSString *city =placemark.locality;

NSString *state =placemark.administrativeArea;

NSString *zip =placemark.postalCode;

// Do something withinformation

geocoder.delegate =nil;

[geocoderautorelease];

}

对于初步接触mapview编程的朋友比较有帮助。

主要知识点:

1.mapview的简单使用。

2.google api的相关调用。

3.mapview大头钉的操作,长按插入大头钉等。

Xcode4.2本地化 总结

1 xcode4.2,如果是简体中文,把国际化的文件放到zh-Hans.lproj中就显示正常了。如果放到zh.lproj中就不可以

2 字符串

1)在项目的“supporting files”目录中右键“new file”然后在弹出窗口左侧选择IOS的resource项,在右侧就可以看到“String File”的图标。创建这个文件,新建的文件名要写成“Localizable.strings” 必须是

2)点击刚才创建的这个文件,选择的菜单中的“view”-》“utilities”-》“file inspect” 右侧会看到一些属性的信息

3)找到Localization这项,现在应该是空的,点“+”进行国际化的添加。因为我只制作了中文和英文,所以我加了“English”和“Chinese”,这里要注意的是“Chinese”要选择“zh_Hans”,这个是简体中文。

4)添加好后就可以看到你项目目录下会生成对应的目录,zh-Hans.lproj和en.lproj 目录里面就是Localizable.strings的文件

5)在项目中可以看到原先创建的Localizable.strings文件的左侧会多出一个三角图标,点击后会扩展出2个文件,一个中文,一个英文的。点击每个文件进行编辑就可以了。

6)文件中的格式是“Key”=“value”; 等号 分号都必须是英文状态。

7)在程序中需要使用国际化字符串的时候,调用NSLocalizedString(@"Key", nil)就可以进行字符串的显示。其中第一个字符串就是文件中的key,第二个字符串可以使用nil代替也可以写一些注释。

3应用程序名称

1)创建一个空文件,取名为InfoPlist.strings 一般程序可以会自动生产 这个文件。

2)对InfoPlist.strings进行。 单击 InfoPlist.strings 。选择 “view”-》“utilities”-》“file inspect” 。 在Localization 选项下 点击+加号

添加chinese(zh-Hans) 类型的 为简体中文 。 english 应该会自动添加上 。 然后在InfoPlish.strings 下会多两个english chinese 版本的文件。

3)在这 english chinese 版本的文件。 编辑不同的InfoPlist.strings文件,设置显示名字

CFBundleDisplayName= "名字";

4)编辑Info.plist,添加一个新的属性Application has localized display name, 设置其类型为boolean,并将其value设置为选中状态

先总结这些

4 nib 文件 和 图片

首先说明一下 图片是不能直接本地化 的。 先把nib文件本地化后 在把相应的图片本地化 过程类似。

本地化nib文件 。 1) 单击 nib文件 然后选择“view”-》“utilities”-》“file inspect” 右侧会看到一些属性的信息。 或者快捷键command + option+ 1。

在Localization选项下 点击+加号 添加chinese (zh-Hans) 类型的 为简体中文 。english 应该会自动添加上 。

本地化图片。 必须先本地化好nib 文件 后 才能本地化相关的图片。 2) 单击图片 。

然后选择“view”-》“utilities”-》“file inspect” 右侧会看到一些属性的信息。 或者快捷键command + option+ 1.

在Localization 选项下 点击+加号 添加chinese(zh-Hans) 类型的 为简体中文 。 english 应该会自动添加上 。

InterfaceBuilder建立UIView无法全屏的解决方法

Interface Builder 默认新建的 XIB 的UIView 是320*460分辨率,所以进入全屏时,底部会出现一个20像素的空白条。就像下图这种效果

解决方法很简单,把分辨率改成320*480即可,比如self.view.frame=CGRectMake(0,0,320,480);

常用Web Service汇总(天气预报、时刻表等)

现成的Web Service中有很多很好用的,比如天气预报,IP地址搜索,火车时刻表等等。本文汇总的一些常用Web Service,希望对大家有所帮助。

天气预报Web Service,数据来源于中国气象局

Endpoint

Disco

WSDL

IP地址来源搜索Web Service(是目前最完整的IP地址数据)

Endpoint

Disco

WSDL

随机英文、数字和中文简体字Web Service

Endpoint

Disco

WSDL

中国邮政编码 <-> 地址信息双向查询/搜索Web Service

Endpoint

Disco

WSDL

验证码图片Web Service 支持中文、字母、数字 图像和多媒体

Endpoint

Disco

WSDL

Email 电子邮件地址验证Web Service

Endpoint

Disco

WSDL

中文简体字 <->繁体字转换Web Service

Endpoint

Disco

WSDL

中文 <-> 英文双向翻译Web Service

Endpoint

Disco

WSDL

火车时刻表Web Service (第六次提速最新列车时刻表)

Endpoint

Disco

WSDL

中国股票行情数据Web Service(支持深圳和上海股市的基金、债券和股票)

Endpoint

Disco

WSDL

即时外汇汇率数据Web Service

Endpoint

Disco

WSDL

腾讯QQ在线状态Web Service

Endpoint

Disco

WSDL

中国电视节目预告(电视节目表)Web Service

Endpoint

Disco

WSDL

外汇-人民币即时报价Web Service

Endpoint

Disco

WSDL

中国股票行情分时走势预览缩略图Web Service

Endpoint

Disco

WSDL

国内飞机航班时刻表 Web Service

Endpoint

Disco

WSDL

中国开放式基金数据Web Service

Endpoint

Disco

WSDL

股票行情数据 Web Service(支持香港、深圳、上海基金、债券和股票;支持多股票同时查询)

Endpoint

Disco

WSDL

向大家推荐一个比较好的网站,http://www.webxml.com.cn/zh_cn/index.aspx。上面又很多好的webservice可以供我们调用。

iphone开发中图像处理四个要点

对于iOS开发者而言,图像处理是一个非常重要的方面。iPhone图像通常存储在以下4个地方:

  相册(PhotoAlums):用户可以使用UIImagePickerController类提供的交互对话框从该相册中获取图像。

  应用程序包:将图像与可执行程序、Info.plist文件和其他资源一同存储,用户可以通过本地文件路径由imageNamed:方法来读取这些基于包的图像。

  沙盒:借助沙盒,可以将文件存储到Documents、Library和tmp文件夹中。

  因特网(Internet):应用程序可通过URL资源从网上下载图像。

  图像文件的位置决定着读取该文件的具体方式。相册中的图片及其路径无法直接从应用程序访问,只有终端用户能够浏览和选择图像,使所选图像对应用程序可用。图像也不能由URL直接初始化。图像源不同读取方式也不同:

  1. 从应用程序包加载图像

  UIImage类提供了一种加载应用程序包中存储的任意图像的简单方法,即通过文件名及其扩展名调用imageNamed:方法。

  myImage = [UIImage imageNamed:@icon.png];

  为避免本地图像缓存及其有效利用内存空间的问题,还可用imageWithContentsOfFile:替换,这个方法会返回从某一具体路径中加载的图像,这个路径需以参数形式提供。当然,若要从应用程序包中获取图像路径,可以查询NSBundle类为给定资源查找路径。示例代码:

NSString *path = [[NSBundle mainBundle] pathForResource:@icon ofType:@png];

myImage = [UIImage imageWithContentsOfFile:path];

  2. 从沙盒加载图像

  默认情况下,每个沙盒包含3个文件夹:Documents、Library和tmp。图像等由应用程序生成的数据通常位于Documents文件夹内。在iPhone开发中可以通过调用实用工具主目录函数可靠地定位顶级沙盒文件夹。通过NSHomeDirectory()返回结果,我们可以向下导航一级到Documents文件夹,完全可以保证正确的位置。示例代码:

NSString *documentsFolder()

  return [NSHomeDirectory()

  stringByAppendingPathComponent:@Documents];

  // 加载图像

  path = [documentsFolder()stringByAppendingPathComponent:@image.png];

  return [UIImage imageWithContentsOfFile:path];

  3. 从URL资源加载图像

  UIImage类可以从NSData实例加载图像,但它不能直接从URL字符串或NSURL对象加载图像。因此,只能为UIImage提供已经从URL下载的数据(即要创建由URL内容初始化的NSData实例)。

  NSURL *url = [NSURLURLWithString:@http://www.cnblogs.com/lovecode/images/demo.jpg];

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url];

  // 类似地我们可以直接创建个类方法

  // 由具体的一个URL字符串,返回通过该资源构建的UIImage

  + (UIImage *) imageFromURLString: (NSString *)urlstring

  return [UIImage imageWithData:[NSDatadataWithContentsOfURL:[NSURL URLWithString:urlstring]]];

  4. 从相册加载数据

  UIImagePickerController类帮助我们从iPhone相册中选择图像。它提供一个独立的视图控制器,以模态形式呈现视图。该控制器发回的委托消息能够反映用户选择的图像。

  UIImagePickerControllerSourceTypePhotoLibrary 所有同步到iPhone的图像以及包括用户拍摄的图片在内的任何相册。

  UIImagePickerControllerSourceTypeSavedPhotosAlbum 仅含相册。

  UIImagePickerControllerSourceTypeCamera 允许用户使用iPhone内置的摄像头拍照。

  图像拾取器的委托必须遵守两个协议:UINavigationControllerDelegate和UIImagePickerControllerDelegate。在接口中一定要为设置为拾取器委托的对象声明这两个协议。

XML解析

CXMLDocument *document;

document = [selfparseXML:@"TouFa.xml"];   //初始化解析XML的对象

NSMutableString *dataStr = [selfparseXMLByName:mystr];

-(CXMLDocument *)parseXML:(NSString*)xmlname

{

NSString*xmlPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:xmlname];

NSData*data = [NSData dataWithContentsOfFile:xmlPath ];

CXMLDocument*docment = [[CXMLDocument alloc]initWithData:data options:0 error:nil];

//   [docmentautorelease];

returndocment;

}

-(NSMutableString*)parseXMLByName:(NSString *)name

{

NSLog(@"%@",name);

NSMutableString*mydata = [[NSMutableString alloc] initWithCapacity:150];

CXMLDocument*record = [document rootElement];

NSArray*root = [record children];

for(CXMLElement *element in root) {

if([element isKindOfClass : [CXMLElement class]]) {

NSMutableDictionary*item = [[NSMutableDictionary alloc]init];

for(int i = 0; i<[element childCount];i++) {

if([[[element children] objectAtIndex:i] isKindOfClass:[CXMLElement class]]) {

[itemsetObject:[[element childAtIndex:i] stringValue] forKey:[[elementchildAtIndex:i] name] ];

}

}

if([name isEqualToString:[item valueForKey:@"ImageName"]]){//名字相等,就是我要找的数据

[mydataappendString: [item valueForKey:@"ID"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Name"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Type"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Sex"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Spirit"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"MeiLi"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Equipment"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"GradeLimit"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Price"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Description"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"Reserve"]];

[mydataappendString: @"|"];

[mydataappendString: [item valueForKey:@"ImageName"]];

}

}

}

[selfAddView:mydata];

[mydataautorelease];

returnmydata;

}

//展示到view上

-(void)AddView:(NSMutableString*) mydata

{

如何获取XML里的第一个节点里的所有子节点值?在WinForm中,根据日期不同,自动获得XML里的值。

操作xml文件的类是 using System.Xml; 中的 XmlDocument    

  以下是一个简单的例子

XmlDocument xml= new XmlDocument();//新建xml对象

xml.Load("xml文件路径"); //载入xml文件路径

XmlNode node =xml.FirstChild; //获取文档的第一个节点

foreach (XmlNoden in node.ChildNodes){    

    string v = n.Value; //节点的值

    string v1 = n.Attributes["属性名"].Value;  //节点属性值

    string v2 = n["元素名"].Value;  //元素值   

  string v3 = n["元素名"].Attributes["属性名"].Value;   //元素属性值

}

NSXMLParser的例子

[pre]<?xml version="1.0"encoding="UTF-8"?>

<users>

<user name="hoge" age="20" />

<user name="fuga" age="30" />

</users>[/pre][pre]代码如下:[/pre][pre]

[pre]static NSString *feedURLString =@"http://www.yifeiyang.net/test/test.xml";

- (void)parserDidStartDocument:(NSXMLParser*)parser

{

// 解析开始时的处理

}

- (void)parseXMLFileAtURL:(NSURL *)URLparseError:(NSError **)error

{

NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:URL];

[parser setDelegate:self];

[parser setShouldProcessNamespaces:NO];

[parser setShouldReportNamespacePrefixes:NO];

[parser setShouldResolveExternalEntities:NO];

[parserparse];

NSError *parseError = [parser parserError];

if(parseError && error) {

*error = parseError;

}

[parser release];

}[/pre][pre]- (void)parser:(NSXMLParser*)parser didStartElement:(NSString *)elementName namespaceURI:[/pre][pre](NSString*)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary*)attributeDict

{

// 元素开始句柄

if(qName) {

elementName = qName;

}

if([elementName isEqualToString:@"user"]) {

// 输出属性值

NSLog(@"Name is %@ , Age is %@", [attributeDictobjectForKey:@"name"], [attributeDictobjectForKey:@"age"]);

}

}

- (void)parser:(NSXMLParser *)parserdidEndElement:(NSString *)elementName namespaceURI:[/pre][pre](NSString*)namespaceURI qualifiedName:(NSString *)qName

{

// 元素终了句柄

if(qName) {

elementName = qName;

}

}

- (void)parser:(NSXMLParser *)parserfoundCharacters:(NSString *)string

{

// 取得元素的text

}

NSError *parseError = nil;

[self parseXMLFileAtURL:[NSURL URLWithString:feedURLString]parseError:&parseError];[/pre]

[/pre]

在iOS中解析XML

以读文件的形式

iOS中的XML是event-driven模式

1:打开一个xml文件,读取内容到NSData中

2:调用NSXMLParse的nitWithData方法,并设置代理tweetParser.delegate = self;

3:调用回调函数

注意:xml文件的第一个tag必须要顶格写!

<?xml version="1.0"encoding="UTF-8"?>    

<bookstore>    

   <bookcatalog="Programming">    

       <titlelang="en">C++ProgrammingLanguage</title>    

       <author>BjarneStroustrup</author>    

       <year>1998</year>    

       <price>98.0</price>   

   </book>    

 <bookcatalog="Networking">    

       <titlelang="en">TCP/IP Illustrated</title>    

       <author>RichardStevens</author>    

       <year>1996</year>    

       <price>56.0</price>   

 </book>    

</bookstore>    

<?xmlversion="1.0"encoding="UTF-8"?> 

<bookstore> 

   <bookcatalog="Programming"> 

       <titlelang="en">C++ Programming Language</title> 

       <author>BjarneStroustrup</author> 

       <year>1998</year> 

       <price>98.0</price> 

   </book> 

 <bookcatalog="Networking"> 

       <titlelang="en">TCP/IP Illustrated</title> 

       <author>RichardStevens</author> 

       <year>1996</year> 

       <price>56.0</price> 

 </book> 

</bookstore>  

详解iOS平台XML解析类库对比和安装说明

详解iOS平台XML解析类库对比和安装说明是本文要介绍的内容。不多说,先来看内容。

在iPhone开发中,XML的解析有很多选择,iOSSDK提供了NSXMLParser和libxml2两个类库,

另外还有很多第三方类库可选,例如TBXML、TouchXML、KissXML、TinyXML和GDataXML。

问题是应该选择哪一个呢?解析XML 通常有两种方式,DOM和SAX:DOM解析XML时,

读入整个XML文档并构建一个驻留内存的树结构(节点树),通过遍历树结构可以检索任意XML节点,

读取它的属性和值。而且通常情况下,可以借助XPath,直接查询XML节点。SAX解析XML,

是基于事件通知的模式,一边读取XML文档一边处理,不必等整个文档加载完之后

才采取操作,当在读取解析过程中遇到需要处理的对象,会发出通知对其进行处理。

一般在iOS平台下,比较常用的XML解析类库有如下几种:

NSXMLParser,http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/

Foundation/Classes/NSXMLParser_Class/Reference/Reference.html,这是一个SAX方式解析XML的类库,

默认包含在iOSSDK中,使用也比较简单。libxml2,

http://xmlsoft.org/,是一套默认包含在iOSSDK中的开源类库,它是基于C语言的API,

所以使用起来可能不如NSXML方便。这套类库同时支持DOM和SAX解析,

libxml2的SAX解析方式还是非常酷的,因为它可以边读取边解析,

尤其是在从网上下载一个很大的XML文件,就可以一边下载一边对已经下载好的内容进行解析,

极大的提高解析效率。TBXML,http://www.tbxml.co.uk/TBXML/TBXML_Free.html,

这是一套轻量级的DOM方式的XML解析类库,有很好的性能和低内存占用,

不过它不对XML格式进行校验,不支持XPath,并且只支持解析,不支持对XML进行修改。

TouchXML,https://github.com/TouchCode/TouchXML,这也是一套DOM方式的XML解析类库,

支持XPath,不支持XML的修改。KissXML,http://code.google.com/p/kissxml/,

这是一套基于TouchXML的XML解析类库,和TouchXML相比,支持了XML的修改。TinyXML,http://www.grinninglizard.com/tinyxml/,

这是一套小巧的基于C语言的DOM方式进行XML解析

的类库,支持对XML的读取和修改,直接支持XPath,需要借助另一个相关的类库TinyXPath才

可以支持XPath。GDataXML,http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/,这是一套Google开发的DOM方式XML解析类库,

支持读取和修改XML文档,支持XPath方式查询。

那么对于如何在项目中选择合适的XML解析类库呢?网上已经有人对这几款XML类库做过分析和对比,

可参考《How To Choose The Best XMLParserfor Your iPhone Project》

http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project一文,

基本比较准确和客观,文中建议:如果是读取很小的XML文档,性能基本上没有什么差别,

不过从调用的方便性来说,建议使用TouchXML、KissXML或GDataXML

如果是需要读取和修改XML文档,建议使用KissXML或GDataXML

如果需要读取非常大的XML文档,则建议使用libxml2或TBXML

如果你不想去调用第三方类库,那么使用NSXML也可以

完整版:http://mobile.51cto.com/iphone-274664.htm

详解iOS平台XML解析类库对比和安装说明

详解iOS平台XML解析类库对比和安装说明是本文要介绍的内容。不多说,先来看内容。

在iPhone开发中,XML的解析有很多选择,iOSSDK提供了NSXMLParser和libxml2两个类库,

另外还有很多第三方类库可选,例如TBXML、TouchXML、KissXML、TinyXML和GDataXML。

问题是应该选择哪一个呢?解析XML 通常有两种方式,DOM和SAX:DOM解析XML时,

读入整个XML文档并构建一个驻留内存的树结构(节点树),通过遍历树结构可以检索任意XML节点,

读取它的属性和值。而且通常情况下,可以借助XPath,直接查询XML节点。SAX解析XML,

是基于事件通知的模式,一边读取XML文档一边处理,不必等整个文档加载完之后

才采取操作,当在读取解析过程中遇到需要处理的对象,会发出通知对其进行处理。

一般在iOS平台下,比较常用的XML解析类库有如下几种:

NSXMLParser,http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/

Foundation/Classes/NSXMLParser_Class/Reference/Reference.html,这是一个SAX方式解析XML的类库,

默认包含在iOSSDK中,使用也比较简单。libxml2,

http://xmlsoft.org/,是一套默认包含在iOSSDK中的开源类库,它是基于C语言的API,

所以使用起来可能不如NSXML方便。这套类库同时支持DOM和SAX解析,

libxml2的SAX解析方式还是非常酷的,因为它可以边读取边解析,

尤其是在从网上下载一个很大的XML文件,就可以一边下载一边对已经下载好的内容进行解析,

极大的提高解析效率。TBXML,http://www.tbxml.co.uk/TBXML/TBXML_Free.html,

这是一套轻量级的DOM方式的XML解析类库,有很好的性能和低内存占用,

不过它不对XML格式进行校验,不支持XPath,并且只支持解析,不支持对XML进行修改。

TouchXML,https://github.com/TouchCode/TouchXML,这也是一套DOM方式的XML解析类库,

支持XPath,不支持XML的修改。KissXML,http://code.google.com/p/kissxml/,

这是一套基于TouchXML的XML解析类库,和TouchXML相比,支持了XML的修改。TinyXML,http://www.grinninglizard.com/tinyxml/,

这是一套小巧的基于C语言的DOM方式进行XML解析

的类库,支持对XML的读取和修改,直接支持XPath,需要借助另一个相关的类库TinyXPath才

可以支持XPath。GDataXML,http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/,这是一套Google开发的DOM方式XML解析类库,

支持读取和修改XML文档,支持XPath方式查询。

那么对于如何在项目中选择合适的XML解析类库呢?网上已经有人对这几款XML类库做过分析和对比,

可参考《How To Choose The Best XMLParserfor Your iPhone Project》

http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project一文,

基本比较准确和客观,文中建议:如果是读取很小的XML文档,性能基本上没有什么差别,

不过从调用的方便性来说,建议使用TouchXML、KissXML或GDataXML

如果是需要读取和修改XML文档,建议使用KissXML或GDataXML

如果需要读取非常大的XML文档,则建议使用libxml2或TBXML

如果你不想去调用第三方类库,那么使用NSXML也可以

完整版:http://mobile.51cto.com/iphone-274664.htm

MKMapView添加图片

以下为两张图片。如下:

适当的代码段添加如下annotation.MapAnnotation是实现了MKAnnotation的NSObject类。

CLLocationCoordinate2Dcoordinate = CLLocationCoordinate2DMake(latitude, longitude);

MapAnnotation*annotation = [[MapAnnotationalloc] initWithcoordiante:coordinate];

[map_viewaddAnnotations: annotation];

[annotationrelease];

图片:3292_120201133909_122.jpg

图片:3292_120201133945_1.jpg

图片:3292_120201134053_1.png

如何在UIAlertView中显示进度条?

今天这个问题是,在一个iPhone程序中,我要在后台做大量的数据处理,希望在界面上显示一个进度条(Progress Bar)使得用户了解处理进度。

这个进度条应该是在一个模态的窗口中,使界面上其他控件无法被操作。怎么用最简单的方法来实现这个功能?UIAlertView是一个现成的模态窗口,

如果能把进度条嵌入到它里面就好了。以下内容适用于iOS 2.0+。我们知道,如果要显示一个alert窗口(比如用来显示错误或警告信息、询问用户是否确认某操作等等),

只要简单地创建一个UIAlertView对象,再调用其show方法即可。示意代码如下:

UIAlertView* alertView = [[[UIAlertViewalloc] initWithTitle:@"Title"

message:@"Message"

delegate:nil

cancelButtonTitle:@"OK"

otherButtonTitles:nil]

autorelease];

[alertView show];

如果要添加一个进度条,只要先创建并设置好一个UIProgressView的实例,再利用addSubbiew方法添加到alertView中即可。

在实际应用中,我可能需要在类中保存进度条的对象实例,以便更新其状态,因此先在自己的ViewController类中添加成员变量:

#import<UIKit/UIKit.h>

@interface MySampleViewController : UIViewController {

@private

UIProgressView* progressView_;

}

@end

接下来写一个叫做showProgressAlert的方法来创建并显示带有进度条的alert窗口,其中高亮的部分就是把进度条添加到alertView中:

- (void)showProgressAlert:(NSString*)titlewithMessage:(NSString*)message {

UIAlertView* alertView = [[[UIAlertViewalloc] initWithTitle:title

message:message

delegate:nil

cancelButtonTitle:nil

otherButtonTitles:nil]

autorelease];

progressView_ = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];

progressView_.frame = CGRectMake(30, 80, 225, 30);

[alertView addSubview:progressView_];

[alertView show];

}

为了让数据处理的子进程能够方便地修改进度条的值,再添加一个简单的方法:

- (void)updateProgress:(NSNumber*)progress {

progressView_.progress = [progress floatValue];

}

另外,数据处理完毕后,我们还需要让进度条以及alertView消失,由于之前并没有保存alertView的实例,可以通过进度条的superview访问之:

- (void)dismissProgressAlert {

if (progressView_ == nil) {

return;

}

if ([progressView_.superview isKindOfClass:[UIAlertViewclass]]) {

UIAlertView* alertView = (UIAlertView*)progressView_.superview;

[alertView dismissWithClickedButtonIndex:0 animated:NO];

}

[progressView_ release];

progressView_ = nil;

}

假设处理数据的方法叫processData,当然它会在一个单独的线程中运行,下面的片段示意了如何更新进度条状态,以及最后如何让它消失。

- (void)processData:(int)total {

for (int i = 0; i < total; ++i) {

// Update UI to show progess.

float progress = (float)i / total;

NSNumber* progressNumber = [NSNumber numberWithFloat:progress];

[self performSelectorOnMainThread:@selector(updateProgress:)

withObject:progressNumber

waitUntilDone:NO];

// Process.

// do it.

}

// Finished.

[selfperformSelectorOnMainThread:@selector(dismissProgressAlert)

withObject:nil

waitUntilDone:YES];

// Other finalizations.

}

在实际使用中,带进度条的alert view大概长得是这样的:

http://www.cocoachina.com/iphonedev/toolthain/2011/1223/3778.html

[ 此帖被haoxue在2012-03-1310:15重新编辑 ]

图片:3292_111223105942_1.png

网上常用免费WebServices集合

天气预报Web服务,数据来源于中国气象局 公用事业

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

中国股票行情分时走势预览缩略图

http://www.webxml.com.cn/webservices/ChinaStockSmallImageWS.asmx

中国股票行情数据 WEB服务(支持深圳和上海股市的基金、债券和股票)

http://www.webxml.com.cn/WebServices/ChinaStockWebService.asmx

国内飞机航班时刻表 WEB服务 公用事业

http://www.webxml.com.cn/webservices/DomesticAirline.asmx

中国电视节目预告(电视节目表) WEB 服务 公用事业

http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx

火车时刻表   (第六次提速最新列车时刻表) 公用事业

http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx

中文<-> 英文双向翻译 WEB 服务 获得标准数据

http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx

验证码图片 WEB服务 支持中文、字母、数字 图像和多媒体

http://www.webxml.com.cn/WebServices/ValidateCodeWebService.asmx

中国邮政编码 <->地址信息双向查询/搜索 WEB 服务 获得标准数据

http://www.webxml.com.cn/WebServices/ChinaZipSearchWebService.asmx

IP地址来源搜索 WEB 服务(是目前最完整的IP地址数据) 获得标准数据

http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx

国内手机号码归属地查询

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

外汇-人民币即时报价

http://webservice.webxml.com.cn/WebServices/ForexRmbRateWebService.asmx

腾讯QQ在线状态 WEB 服务

http://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx

中文简体字<->繁体字转换 WEB 服务

http://webservice.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx

IP地址搜索 WEB 服务包含中国和国外已知的IP地址数据,是目前最完整的IP地址数据,记录数量现已超过37万条并还在不断更新和增加中

http://webservice.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx

UIAlertView(警告)的创建

initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:

注释:initWithTitle是对象函数

initWithTitle:警告框标题

message:警告内容

delegate:接收对象

cancelButtonTitle:关闭按钮标题

otherButtonTitles:其他按钮

iphone开发 UIButton使用

UIButton状态:

UIControlStateNormal         // 正常状态  

UIControlStateHighlighted    // 高亮状态  

UIControlStateDisabled       // 禁用状态   

UIControlStateSelected       // 选中状态   

UIControlStateApplication    //    

UIControlStateReserved       // 保留状态

UIButton类型:

UIButtonTypeCustom           //自定义类型

[pre]添加图片: [/pre][pre]

[pre]灰色背景颜色:[/pre]

[pre]UIButtonTypeRoundedRect      //圆角类型[/pre]

 UIButtonTypeDetailDisclosure  //细节展示按钮

UIButtonTypeInfoLight         //浅色背景的信息按钮

UIButtonTypeInfoDark          //暗色背景的信息按钮

UIButtonTypeContactAdd        // 添加按钮 www.2cto.com

创建UIButton 1. UIButton *button = [[UIButton alloc]initWithFrame: CGRectMake (x, y, Width, Height)];      2.UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];   设置UIButton标题 [button setTitle:titleforState:UIControlStateNormal];      设置UIButton标题颜色 [buttonsetTitleColor:[UIColor blackColor] forState:UIControlStateNormal];   设置UIButton背景图片 [buttonsetBackgroundImage:newImage forState:UIControlStateNormal];   设置UIButton背景颜色 button.backgroundColor =[UIColor clearColor];

 

 

[/pre]

iPhone开发笔记 退回输入键盘:自定义颜色:隐藏状态栏:

 

退回输入键盘:

 

 - (BOOL) textFieldShouldReturn:(id)textField{

   [textField  resignFirstResponder];

}

 

CGRect

CGRect frame =CGRectMake (origin.x, origin.y, size.width, size.height);矩形

NSStringFromCGRect(someCG)把CGRect结构转变为格式化字符串;

CGRectFromString(aString)由字符串恢复出矩形;

CGRectInset(aRect)创建较小或较大的矩形(中心点相同),+较小  -较大

CGRectIntersectsRect(rect1,rect2) 判断两矩形是否交叉,是否重叠

CGRectZero 高度和宽度为零的/位于(0,0)的矩形常量

 

CGPoint &CGSize

CGPoint aPoint= CGPointMake(x, y);    CGSize aSize = CGSizeMake(width, height);

 

设置透明度 [myView setAlpha:value];  (0.0 < value < 1.0)

设置背景色 [myViewsetBackgroundColor:[UIColor redColor]]; 

   (blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;

orangeColor;purpleColor;brownColor;clearColor; )

自定义颜色:

UIColor*newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float)alpha:(float)];      0.0~1.0

 

 

 

  320X480     480X320    状态栏高 20 像素高   导航栏 工具栏 44像素高

隐藏状态栏:

[[UIApplicationshareApplication] setStatusBarHidden: YES animated:NO]

 

横屏:

[[UIApplicationshareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

orientation ==UIInterfaceOrientationLandscapeLeft

window=[[UIWindowalloc] initWithFrame:[UIScreen mainScreen] bounds];全屏

 

自动适应父视图大小:

aView.autoresizingSubviews= YES;

aView.autoresizingMask= (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

 

 定义按钮

UIButton *scaleUpButton= [UIButton buttonWithType:UIButtonTypeRoundedRect];

[scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal];

scaleUpButton.frame = CGRectMake(40, 420, 100, 40);

[scaleUpButton addTarget:self action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside];

 

设置视图背景图片

UIImageView*aView;

[aViewsetImage:[UIImage imageNamed:@”name.png”]];

view1.backgroundColor= [UIColor colorWithPatternImage:[UIImage imageNamed:@"image1.png"]];

 

UISlider *slider= (UISlider *) sender;

NSString*newText = [[NSString alloc] initWithFormat:@”%d”, (int)(slider.value + 0.5f)];

label.text =newText;

 

活动表单 <UIActionSheetDelegate>

 

 

- (IBActive)someButtonPressed:(id) sender

{

   UIActionSheet *actionSheet = [[UIActionSheet alloc] 

                   initWithTitle:@”Are yousure?”

                   delegate:self

                   cancelButtonTitle:@”Noway!”

                  destructiveButtonTitle:@”Yes, I’m Sure!”

                   otherButtonTitles:nil];

   [actionSheet showInView:self.view];

   [actionSheet release];

}

 

警告视图 <UIAlertViewDelegate>

 

 

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex

{

    if(buttonIndex != [actionSheet cancelButtonIndex])

    {

         NSString *message = [[NSString alloc] initWithFormat:@”Youcan          

                  breathe easy,everything went OK.”];

         UIAlertView *alert = [[UIAlertView alloc]    

                             initWithTitle:@”Something was done”

                              message:message

                              delegate:self

                              cancelButtonTitle:@”OK”

                              otherButtonTitles:nil];

         [alert show];

         [alert release];

         [message release];

    }

}

 

动画效果

-(void)doChange:(id)sender

{

if(view2 == nil)

{

[self loadSec];

}

[UIViewbeginAnimations:nil context:NULL];

[UIViewsetAnimationDuration:1];        

[UIViewsetAnimationTransition:([view1 superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.viewcache:YES];

 

   if([view1 superview]!= nil)

{

[view1 removeFromSuperview];

[self.viewaddSubview:view2];

 

}else {

 

[view2 removeFromSuperview];

[self.viewaddSubview:view1];

}

[UIViewcommitAnimations];

}

一些iOS高效开源类库

因为iOSSDK相对比较底层,所以开发者就得受累多做一些体力活。不过幸运的是,有很多第三方的类库可以用来简化很多不必要的工作。整理了一下在本人学习过程中用到的一些比较有用Objective-C开源类库,既是做一个总结,同时也希望通过这些分享,能提高各位的开发效率。

KissXml——xml解析库

相关教程:http://www.iteye.com/topic/625849

http://sencho.blog.163.com/blog/static/83056228201151743110540/

很方便的一个xml解析器,支持Xpath查询。

skpsmtpmessage——Quick SMTP邮件发送

svn checkout http://skpsmtpmessage.googlecode.com/svn/trunk/ skpsmtpmessage-read-only

github:      git clone https://github.com/kailoa/iphone-smtp.git

相关教程:http://disanji.net/2011/01/28/skpsmtpmessage-open-source-framework/

skpsmtpmessage 是由Skorpiostech, Inc.为我们带来的一个SMTP协议的开源实现,使用Objective-c实现,iOS系统的项目可以直接调用。

jsonframework——JSON支持

相关教程:http://blog.csdn.net/xiaoguan2008/article/details/6732683

它是一个开源框架,基于BSD协议发布。由于json-framework是开放源代码的,当你需要使用它时你只需将json的源代码加入到你的工程中。

ASIHttpRequest——HTTP Network库

ASIHttpRequest库极大的简化了网络通 信,提供更先进的工具,例如文件上传工具,重定向处理工具、验证工具、等等。

MBProgressHUD——进展指示符库

苹果的应用程序一般都会用一种优雅的,半透明的进度显示效果,不过这个API是不公开的,因此你要是用了,很可能被清除出AppStore。而 MBProgressHUD提供了一个替代方案,而且在用户角度上,实现的效果根本看不出和官方程序有什么差别。同时还提供了其他附加功能,比如虚拟进展 指示符,以及完成提示信息。整合到项目里也很容易,这里不细谈了。

zxing——二维码扫描库

支持条形码/二维码扫描的图形处理库,这是一个java库,在android上的功能比较完整。同时该库也支持ios,但只能支持二位条形码的扫描。

kal——iPhone日历控件

一个类似于ios系统默认日历开源日历库,支持添加事件,自定义日历样式等功能。

Facebook iOS SDK——Facebook API类库

大体来讲就是iPhone上的Facebook login,完全支持Facebook Graph API和the older REST api。

shareKit——分享库

相关demo:http://www.cocoachina.com/bbs/read.php?tid-71760.html

分享到开心,豆瓣,腾讯,新浪微博的api所用到的强大的分享库。

SDWebImage——简化网络图片处理

用SDWebImage调用网站上的图片,跟本地调用内置在应用包里的图片一样简单。操作也很简单。

GDataclient——iPhone上所有Google相关服务的类库

名字就说明一切了。跟Google相关的,值得一提的是,这个项目很开放。有很多示例程序供下载。

CorePlot——2D图形绘图仪

CorePlot有很多解决方案将你的数据可视。同时也会提供各种迷人的图形效果,比如棒状图、饼状图、线状图等等,在他们网站上也提供了大量的范例图形,很多股票价格应用,游戏分数,个人财务管理都在用。

Three20——类似于Facebook的优秀的UI库

Three20类库是Facebook自己做的,大而全是他最大的特色。把他整合到已有的项目中可能得费点周折,不过如果一开始你就用上了Three20,尤其是牵扯到很多web相关的项目的时候,你就能深刻体会到神马叫给力了。

FMDatabase——SQLite的Objective-C封装

是SQLite的C API對初學者來說實在太麻煩太瑣碎,難度太高。FMDB說穿了其實只是把C API包裝成簡單易用的Objective-C类。對于SQLite初學者來說,大大減低了上手的難度。有了FMDB,寫程式時只要專心在SQLite的語法上,而不用去理那堆有看沒有懂的C API,實在是件快樂的事情。

iPhone开发之 - [UIView beginAnimations:context:]与[UIView animateWithDuration:animations:]值得注意区别

看过官方文档的都知道,官方推荐在iOS4以后使用[UIView animateWithDuration:animations:],而不是原来的[UIView beginAnimations:context:],来完成动画,虽然二者功能几乎完全相同,但使用前者在一些情况下会方便不少,这些内容可以参考官方文档View Programming Guide For iOS的Animation一节.

二者有一个值得新手注意的区别就是[UIViewanimateWithDuration:animations:]默认会禁止触摸,手势等的响应,这可以通过设置option选项来解决(直接引用StackOverFlow的一段了):

 

UIViewAnimationOptions options =UIViewAnimationCurveLinear | UIViewAnimationOptionAllowUserInteraction;

[UIView animateWithDuration:0.2delay:0.0 options:options animations:^

{

highlightView.alpha= 1.0;

} completion:nil];

 

[UIViewanimateWithDuration:duration

delay:0.0

options:UIViewAnimationCurveEaseInOut//设置动画类型

animations:^{

//开始动画

[selfupdateArrowBtnTitle:YES];

rotateView.transform= CGAffineTransformMakeRotation((stickToDegrees/180)*M_PI);

}

completion:^(BOOLfinished){

//动画结束时的处理

}];

[UIView animateWithDuration:] 方法仅支持ios4.0及以上版本。如果要兼容以前的版本的话,还是需要使用 [UIView beginAnimation:] 方法

 

[UIView beginAnimations:nilcontext:nil];

// fadeout

helpImageBtn.alpha= 0.0f;

// setanimation did stop selector

[UIViewsetAnimationDelegate:self];

[UIViewsetAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

[UIViewcommitAnimations];

-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finishedcontext:(void *)context {

if(self.retainedHelpImageBtn.superview) //先判断父视图再执行视图移除

[self.retainedHelpImageBtnremoveFromSuperview];

}

判断textField为空时让按钮不可用的代码

textField 为空时让按钮不可用,既防止误操作又显得应用很注重细节。

-(BOOL)textField:(UITextField *)textFieldshouldChangeCharactersInRange:(NSRange)range

replacementString:(NSString*)string

{

NSMutableString*newValue = [[self.TextField.text mutableCopy] autorelease];

[newValuereplaceCharactersInRange:range withString:string];

if ([newValuelength]== 0) {

self.navigationItem.rightBarButtonItem.enabled= NO;

}

else {

self.navigationItem.rightBarButtonItem.enabled= YES;

}

return YES;

}

-(BOOL)textFieldShouldClear:(UITextField *)textField{

self.navigationItem.rightBarButtonItem.enabled= NO;

return YES;

}

如何自定义UIActionSheet(UIAlertView)中的内容

UIActionSheet和UIAlertView因为UI有特殊的用途,所以本身并不允许你AddSubview之类的函数来自定义界面。

解决的办法是继承它,实现一个自定义类,重载layoutSubviews函数

#import <UIKit/UIKit.h>@interface UIImageActionSheet : UIActionSheet {

UIImage *titleImage;

}

-(id) initWithImage:(UIImage *)image

title:(NSString *)title

delegate:(id <UIActionSheetDelegate>)delegatecancelButtonTitle:(NSString *)cancelButtonTitle

destructiveButtonTitle:(NSString *)destructiveButtonTitle

otherButtonTitles:(NSString *)otherButtonTitles;

@end

#import "UIImageActionSheet.h"@implementation UIImageActionSheet

-(id) initWithImage:(UIImage *)image

title:(NSString *)title

delegate:(id <UIActionSheetDelegate>)delegatecancelButtonTitle:(NSString *)cancelButtonTitle

destructiveButtonTitle:(NSString *)destructiveButtonTitle

otherButtonTitles:(NSString *)otherButtonTitles{

self =[super initWithTitle:title delegate:delegatecancelButtonTitle:cancelButtonTitle

destructiveButtonTitle:destructiveButtonTitle

otherButtonTitles:otherButtonTitles,nil];

if(self) {

titleImage=image;

[titleImage retain];

UIImageView *imageView =[[UIImageView alloc] initWithImage:titleImage];

imageView.frame =CGRectZero;

//for(UIView *subView inself.subviews){

if(![subView isKindOfClass:[UILabel class]]) {

[self insertSubview:imageView aboveSubview:subView];

break;

}

}

[imageView release];

}

returnself;

}

-(CGFloat) maxLabelYCoordinate {

//Determine maximum y-coordinate of labelsCGFloat maxY =0;

for( UIView *view inself.subviews ){

if([view isKindOfClass:[UILabel class]]) {

CGRect viewFrame =[view frame];

CGFloat lowerY =viewFrame.origin.y +viewFrame.size.height;

if(lowerY >maxY)

maxY =lowerY;

}

}

returnmaxY;

}

-(void) layoutSubviews{

[super layoutSubviews];

CGRect frame =[self frame];

CGFloat labelMaxY =[self maxLabelYCoordinate];

for(UIView *view inself.subviews){

if(![view isKindOfClass:[UILabel class]]) {

if([view isKindOfClass:[UIImageView class]]){

CGRect viewFrame =CGRectMake((320-titleImage.size.width)/2, labelMaxY +10,

titleImage.size.width, titleImage.size.height);

[view setFrame:viewFrame];

}

elseif(![view isKindOfClass:[UIImageView class]]) {

CGRect viewFrame =[view frame];

viewFrame.origin.y +=titleImage.size.height+10;

[view setFrame:viewFrame];

}

}

}

frame.origin.y -=titleImage.size.height +2.0;

frame.size.height +=titleImage.size.height +2.0;

[self setFrame:frame];

}

/*// 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];

if(titleImage) {

[titleImage release];

}

}

@end

使用:

UIImage *tips3Img =[UIImage imageNamed:@"tips-3.png"];

UIImageActionSheet *tipsActionSheet =[[UIImageActionSheet alloc]

initWithImage:tips3Img

title:@"添加的图案可用以下方式调整"delegate:self cancelButtonTitle:@"知道了"destructiveButtonTitle:nil

otherButtonTitles:nil];

tipsActionSheet.tag =kActionSheetTagTips;

[tipsActionSheet showInView:self.view];

[tipsActionSheet release];

效果:

图片:自定义UIActionSheet(UIAlertView)中的内容.png

IOS开发UI篇之──自定义加载等待框(MBProgressHUD)

这里介绍一下网友开源的MBProgressHUD类,实现等待框,

一、网上下载  MBProgessHUD 类文件,直接导入到工程即可

二、示例分析

在我的工程中示例如下:

1)在ShowImageViewController.h头文件代码如下:

#import <UIKit/UIKit.h>

#import "MBProgressHUD.h"

@interface ShowImageViewController: UIViewController<MBProgressHUDDelegate> {

NSString        *_picUrlString;

UIImageView     *_imageView;

MBProgressHUD    *_progressHUD;

}

@property (nonatomic, copy) NSString      *picUrlString;

@property (nonatomic, retain) IBOutletUIImageView *imageView;

@property (nonatomic, retain) MBProgressHUD   *progressHUD;

//请求图片资源

-(void)imageResourceRequest;

//显示图片信息

-(void)displayImage:(UIImage *)image;

- (IBAction)dismissModealView:(id)sender;

-(void)removeModalView;

@end

2)在ShowImageViewController.m实现文件代码如下:

#import"ShowImageViewController.h"

#import<QuartzCore/QuartzCore.h>

@implementationShowImageViewController

@synthesize picUrlString =_picUrlString;

@synthesize imageView =_imageView;

@synthesize progressHUD =_progressHUD;

- (void)viewDidLoad

{

[superviewDidLoad];

// Do anyadditional setup after loading the view from its nib.

self.view.backgroundColor = [UIColor grayColor];

self.view.alpha= 0.8;

//设置图片为圆角

self.imageView.backgroundColor = [UIColor clearColor];

self.imageView.layer.borderColor= [UIColor lightGrayColor].CGColor;

self.imageView.layer.borderWidth= 5.0;

self.imageView.layer.masksToBounds = YES;

self.imageView.layer.cornerRadius = 10.0;

}

-(void)viewWillAppear:(BOOL)animated

{

[superviewWillAppear:animated];

//当进入视图时,重新设置imageView

[self.imageViewsetImage:nil];

[self.imageViewsetFrame:CGRectMake(160, 200, 0, 0)];

//显示加载等待框

self.progressHUD= [[MBProgressHUD alloc] initWithView:self.view];

[self.viewaddSubview:self.progressHUD];

[self.viewbringSubviewToFront:self.progressHUD];

self.progressHUD.delegate =self;

self.progressHUD.labelText =@"加载中...";

[self.progressHUD show:YES];

//开启线程,请求图片资源

[NSThreaddetachNewThreadSelector:@selector(imageResourceRequest) toTarget:selfwithObject:nil];

}

//请求图片资源

-(void)imageResourceRequest

{

NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];

//根据网络数据,获得到image资源

NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURLURLWithString:self.picUrlString]];

UIImage *image =[[UIImage alloc] initWithData:data];

[data release];

//回到主线程,显示图片信息

[selfperformSelectorOnMainThread:@selector(displayImage:) withObject:imagewaitUntilDone:NO];

[image release];

[pool release];

}

//显示图片信息

-(void)displayImage:(UIImage*)image

{

//若self.progressHUD为真,则将self.progressHUD移除,设为nil

if(self.progressHUD){

[self.progressHUD removeFromSuperview];

[self.progressHUD release];

self.progressHUD = nil;

}

//图片慢慢放大动画效果

[self.imageViewsetImage:image];

[UIViewbeginAnimations:nil context:nil];

[UIViewsetAnimationDuration:0.5];

[self.imageView setFrame:CGRectMake(40,100, 240, 160)];

[UIView commitAnimations];

}

- (void)viewDidUnload

{

[selfsetImageView:nil];

[superviewDidUnload];

// Release anyretained subviews of the main view.

// e.g.self.myOutlet = nil;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

// Return YESfor supported orientations

return(interfaceOrientation == UIInterfaceOrientationPortrait);

}

-(IBAction)dismissModealView:(id)sender {

//设置定时器,当动画结束时,子视图从父视图中移除

[NSTimerscheduledTimerWithTimeInterval:0.5 target:selfselector:@selector(removeModalView) userInfo:nil repeats:NO];

[UIViewbeginAnimations:nil context:nil];

[UIViewsetAnimationDuration:0.5];

[self.imageView setFrame:CGRectMake(160,200, 0, 0)];

[UIView commitAnimations];

}

-(void)removeModalView

{

[self.viewremoveFromSuperview];

}

#pragma mark -

#pragma markMBProgressHUDDelegate methods

-(void)hudWasHidden:(MBProgressHUD *)hud {

NSLog(@"Hud: %@",hud);

// Remove HUDfrom screen when the HUD was hidded

[self.progressHUD removeFromSuperview];

[self.progressHUD release];

self.progressHUD= nil;

}

- (void)dealloc

{

[_picUrlString release];

[_imageView release];

[super dealloc];

}

@end

三、效果展示

四、总结

利用MBProgressHUD实现加载等待框,视觉效果大大提高

图片:自定义加载等待框(MBProgressHUD).png

用代码实现UILabel和UISlider功能

首先在。h的文件面加入如下代码:

声明变量:

IBOutlet UILabel *lab;

IBOutlet UISlider *slid;

IBOutlet UITextField *txt;

IBOutlet UISlider *red;

IBOutlet UISlider *green;

IBOutlet UISlider *blue;

定义方法:

-(IBAction)add;

-(IBAction)addred;

-(IBAction)addgreen;

-(IBAction)addblue;

然后在。m的文件中加入下面方法的实现:

-(void)viewDidLoad//初始化设定

{

lab.text=@"123456789";//设定Lable的初始值

slid.minimumValue=12;//设定字体的最下值

slid.maximumValue=50;//设定字体的最大值

red.minimumValue=0;//设定Red的最小值为0

red.maximumValue=1;//设定Red的最大值为1

blue.minimumValue=0;//设定Blue的最小值为0

blue.maximumValue=1;//设定Blue的最大值为1

green.minimumValue=0;//设定Green的最小值为0

green.maximumValue=1;//设定Green的最打值为1

[lab setFont:[UIFontfontWithName:@"DBLCDTempBlack" size:[slid value]]];//初始化Label的字体和大小

[super viewDidLoad];

}

- (void)didReceiveMemoryWarning

{

[superdidReceiveMemoryWarning];

}

-(void)add//控制字体的大小

{

int i=[slid value];//得到UISlider的值

[lab setFont:[UIFontfontWithName:@"DBLCDTempBlack" size:i]];//设定Label的字体和大小

txt.text=[NSStringstringWithFormat:@"%d",i];//调试阶段弄个TextField用来显示大小

}

-(IBAction)addred//根据UISlider的值来设置Red的值

{

float r=[red value];

float g=[green value];

float b=[blue value];

[lab setTextColor:[UIColorcolorWithRed:r green:g blue:b alpha:1]];

}

-(IBAction)addgreen

{

float r=[red value];

float g=[green value];

float b=[blue value];

[lab setTextColor:[UIColorcolorWithRed:r green:g blue:b alpha:1]];

}

-(IBAction)addblue

{

float r=[red value];

float g=[green value];

float b=[blue value];

[lab setTextColor:[UIColorcolorWithRed:r green:g blue:b alpha:1]];

}

- (void)dealloc

{

[lab release];

[slid release];

[red release];

[blue release];

[green release];

[super dealloc];

}

最终的效果图:

图片:UILabel和UISlider的一点用法.png

UISlider *mySlider =[[UIslider alloc] initwith...];

[self.viewaddsubview:myslider];

[mySlider release];

UISlider *slider = [[[UISlideralloc] initWithFrame:CGRectMake(50, 50, 100, 40)] autorelease];

[slider addTarget:selfaction:@selector(controlValueChanged:)forControlEvents:UIControlEventValueChanged];

slider.minimumValue = 100.00;

slider.maximumValue = 1000.00;

slider.continuous = YES;

[self.view addSubview:slider];

UISlider滑块控件

UISlider实例提供一个控件,让用户通过左右拖动一个滑块(可称其为“缩略图”)来选择一个值。默认情况下,滑块的最小值为0.0,最大值为1.0。

当然可以在属性面板中通过设置minimumValuemaximumValue来进行定制这两个值。如果要为控件两端设置样式,可以添加一对相关图像(minimumValueImagemaximumValueImage属性)来加强该设置,也可在代码中通过setMimimumTrackImage: forState: 和setMaximumTrackImage: forState: 方法来添加设置两端图片。

滑块的continuous属性控制在用户拖动缩略图时一个滑块是否持续发送值更新。设置为NO(默认为YES)时,用户释放缩略图时滑块仅发送一个动作事件。UISlider类还允许直接更新其缩略图组件,通过调用setThumbImage: forState:方法可定制自己的滑块图片。

自定义UISlider的样式和滑块的代码:

[pre]//左右轨的图片

UIImage*stetchLeftTrack = [UIImage imageNamed:@"snow_bar.png"];

UIImage*stetchRightTrack = [UIImage imageNamed:@"sun_bar.png"];

//滑块图片

UIImage *thumbImage =[UIImage imageNamed:@"mark.png"];

UISlider *slider =[[UISlider alloc] initWithFrame:CGRectMake(30,320,257,7)];

slider.backgroundColor= [UIColor clearColor];

slider.value = 1.0;

slider.minimumValue =0.7;

slider.maximumValue =1.0;

[slidersetMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];

[slidersetMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];

//注意这里务必加上UIControlStateHightlighted的状态,否则当拖动滑块时滑块将变成原生的控件

[slidersetThumbImage:thumbImage forState:UIControlStateHighlighted];

[slidersetThumbImage:thumbImage forState:UIControlStateNormal];

//滑块拖动时的事件

[slider addTarget:selfaction:@selector(sliderValueChanged:)forControlEvents:UIControlEventValueChanged];

//滑块拖动后的事件

[slider addTarget:selfaction:@selector(sliderDragUp:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:slider];

UISlider按钮透明

今天要实现一个UISlider 按钮透明的效果 折腾了几个小时才发现原来很简单,嘎嘎

 我们普通的效果是这样的手指可以滑动按钮 现在要实现将这个按钮透明话,如图

 

 看不到圆形的按钮 但依然可以在上面拖动,其实现原理非常简单,代码如下:

 

   [slidersetThumbImage:[UIImageimageNamed:@"test.png"]forState:UIControlStateNormal];

   [slidersetThumbImage:[UIImageimageNamed:@"test.png"]forState:UIControlStateHighlighted];

   代码是给按钮加载了一张图片 而这张图片是空的 所以按钮就看不到了,嘎嘎

图片:0_1320655878Y5nz.gif

图片:0_132065593578Xmqqq.gif

UISlider使用方法

代码:

#import <UIKit/UIKit.h>

@interface ControlViewController: UIViewController {

UILabel *sliderLabel;

}

@property (nonatomic,retain) IBOutlet UILabel*sliderLabel;

-(IBAction)sliderChanged:(id)sender;

@end

@implementation ControlViewController

@synthesize sliderLabel;

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

-(IBAction)sliderChanged:(id)sender

{

//首先将sender装换承UISlider,作用是让代码可读性变强,

//并避免每次使用sender都对他进行其它类型转换。

UISlider *slider = (UISlider *)sender;

//接收滑块的值,将其加0.5,以便四舍五入为整型值。

int progresAsInt =(int)(slider.value +0.5f);

NSString *newText =[[NSString alloc]initWithFormat:@"%d",progresAsInt];

sliderLabel.text = newText;

[newText release];

}

- (void)dealloc {

[sliderLabel release];

[super dealloc];

}

@end

进入Interface Builder,加入Label和Slider两个组件。并分别进行设置:

Label:

Slider:

绑定sliderLabel:

绑定ValueChanged事件到sliderChanged操作:

NSLog("Success!!");

图片:67b061baha09e6f7e186e&690.png

图片:67b061baha09e75.png

图片:67b061baha09e75403bd9&690111.png

将UIPickerView横放到UIActionSheet中

如何将UIPickerView调整大小后放入UIActionSheet中,我成功的实现了,现将代码贴出来。

UIActionSheet*actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择自动选取号码的个数:\n\n\n\n"

delegate:selfcancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK"otherButtonTitles:nil];

actionSheet.actionSheetStyle= UIActionSheetStyleDefault;

statesarray =[[NSArray alloc] initWithObjects:@"1", @"2",@"3",@"4", @"5", @"6",@"7",@"8", @"9", @"10",nil];

picker =[[UIPickerView alloc] initWithFrame:CGRectMake(0, -40, 100.0, 320.0)];

picker.delegate =self;

picker.showsSelectionIndicator=YES;

//picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;

picker.backgroundColor= [UIColor clearColor];

CGAffineTransformrotate = CGAffineTransformMakeRotation(3.14/2);//调整角度180度,横向。

rotate =CGAffineTransformScale(rotate, 0.10, 2.0);//调整大小

[pickersetTransform:rotate];

[actionSheetaddSubview:picker];

[picker release];

[actionSheetshowInView:self.view];

[actionSheet release];

#pragma mark -

#pragma mark PickerData Source Methods

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

return 1;

}

-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component

{

return [statesarraycount];

}

#pragma mark PickerDelegate Methods

/*

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)rowforComponent:(NSInteger)component

{

return[self.statesarray objectAtIndex:row];

}*/

-(UIView *)pickerView:(UIPickerView*)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)componentreusingView:(UIView *)view{

CGRect rect =CGRectMake(0, 0, 160, 160);

UILabel *label =[[[UILabel alloc]initWithFrame:rect] autorelease];

CGAffineTransform rotate= CGAffineTransformMakeRotation(-3.14/2);;//调整角度-180度,横向。

rotate =CGAffineTransformScale(rotate, 0.10, 2.0);;//调整大小

[labelsetTransform:rotate];

label.text =[statesarray objectAtIndex:row];

label.font = [UIFontsystemFontOfSize:68.0];

label.textAlignment =UITextAlignmentCenter;

label.numberOfLines =0;

label.lineBreakMode =UILineBreakModeWordWrap;

label.backgroundColor= [UIColor clearColor];

label.clipsToBounds =YES;

return label ;

}

UIPickerView使用DEMO

@interface Set_starViewController: UIViewController<UIPickerViewDelegate>{

UIPickerView*pickerview;

UILabel *contentview;

NSArray  *content;//星座

id _delegate;

int _type;

}

-(id)initWithDelegate:(id)delegatetype:(int)type;

- (void)setString:(id)sender;

@end

#import "Set_starViewController.h"

@implementation Set_starViewController

-(id)initWithDelegate:(id)delegatetype:(int)type

{

self = [super init];

if (self != nil){

UILabel *titleText =[[UILabel alloc] initWithFrame: CGRectMake(0, 0, 200, 20)];

titleText.backgroundColor =[UIColor clearColor];

titleText.textAlignment = UITextAlignmentCenter;

titleText.textColor =[UIColor colorWithRed:0.33 green:0.33 blue:0.33 alpha:1.0];

[titleText setFont:[UIFont systemFontOfSize:15.0]];

[titleText setText:@"星座"];

self.navigationItem.titleView=titleText;

[titleText release];

_delegate = delegate;

UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(0.0,0.0, 62.0, 32.0)];

[back setBackgroundImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal];

[back setBackgroundImage:[UIImage imageNamed:@"返回按钮按下.png"] forState:UIControlStateHighlighted];

[back setBackgroundImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateDisabled];

[back addTarget:_delegate

action:@selector(backView)

forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *add =[[UIBarButtonItem alloc] initWithCustomView:back];

[[self navigationItem] setLeftBarButtonItem:add];

[add release];

[back release];

UIBarButtonItem *save = nil;

save = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave

target:self

action:@selector(setString:)];

self.navigationItem.rightBarButtonItem =save;

save = nil;

[save release];

if (type == 0) {

content = [[NSArray alloc]initWithObjects:@"水瓶座",@"双鱼座",@"白羊座",@"金牛座"

,@"双子座",@"巨蟹座",@"狮子座",@"处女座"

,@"天秤座",@"天蝎座",@"射手座",@"山羊座",nil];

_type = 0;

}else {

content = [[NSArray alloc]initWithObjects:@"初中",@"高中",@"中技",@"中专",@"大专",@"本科",@"MBA",@"硕士"

,@"其他",nil];

_type = 1;

}

}

return self;

}

-(void) loadView

{

UIView*myview = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]autorelease];

myview.autoresizesSubviews =YES;

[myview setBackgroundColor:[UIColor colorWithPatternImage:[UIImageimageNamed:@"background.png"]]];

self.view  = myview;

// 设置选择器

pickerview = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0,150.0, 320.0, 216.0)];

pickerview.delegate = self;

pickerview.showsSelectionIndicator =YES;

[self.view addSubview:pickerview];

contentview = [[UILabel alloc] initWithFrame:CGRectMake(80.0,80.0, 100.0, 40.0)];

contentview.backgroundColor =[UIColor clearColor];

[self.view addSubview: contentview];

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

- (void)viewDidUnload {

[super viewDidUnload];

// Release any retainedsubviews of the main view.

// e.g. self.myOutlet =nil;

}

- (void)dealloc {

[super dealloc];

[contentview release];

[pickerview release];

[content release];

}

#pragma mark -

#pragma mark 处理方法

//返回显示的列数

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView

{

return 1;

}

//返回当前列显示的行数

-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component

{

return [content count];

}

// 设置当前行的内容,若果行没有显示则自动释放

- (NSString *)pickerView:(UIPickerView *)pickerViewtitleForRow:(NSInteger)row forComponent:(NSInteger)component

{

return [content objectAtIndex:row];

}

- (void)pickerView:(UIPickerView *)pickerViewdidSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

//NSString *result = [pickerViewpickerView:pickerView titleForRow:row forComponent:component];

NSString  *result = nil;

result = [contentobjectAtIndex:row];

NSLog(@"result:%@",result);

contentview.text = result;

[result release];

}

- (void)setString:(id)sender

{

//传递值

if (_type ==0) {

[_delegate setSomthing:contentview.textname:@"star"];

}else {

[_delegate setSomthing:contentview.textname:@"xueli"];

}

[self.navigationController popViewControllerAnimated:YES];

[self.navigationController pushViewController:_delegate animated:YES];

[self.navigationController setNavigationBarHidden:NO];

}

@end

[ 此帖被haoxue在2012-02-2001:11重新编辑 ]

图片:UIPickerView使用DEMO.png

iphone开发-自定义frame,添加toolbar和pickerview

自定义的frame  pickerv.h文件

#import <UIKit/UIKit.h>

#import <QuartzCore/QuartzCore.h>

@interface pickerv : UIView<UIPickerViewDelegate>{

UIToolbar *toolBar;

UIPickerView *picker;

NSArray *pickerArr;

CGRect closeView;

CGRect openView;

BOOL isOpen;

NSString *selectedStr;

}

@property (nonatomic, retain) IBOutlet UIToolbar*toolBar;

@property (nonatomic, retain) IBOutlet UIPickerView*picker;

@property (nonatomic, retain)NSArray *pickerArr;

@property (nonatomic, retain)NSString *selectedStr;

@property BOOL isOpen;

-(void)viewOpen;

-(void)viewClose;

-(void)cancle;

-(void)done;

@end

pickerv.m文件

#import "pickerv.h"

@implementation pickerv

@synthesize toolBar,picker,pickerArr,isOpen,selectedStr;

- (id)initWithFrame:(CGRect)frame {

self = [super initWithFrame:frame];

if (self){

isOpen = NO;

closeView = self.frame;

openView = CGRectMake(closeView.origin.x, closeView.origin.y-260,closeView.size.width, 260);

[self setClipsToBounds:YES];

[self setBackgroundColor:[UIColor whiteColor]];

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, closeView.size.width,44)];

toolBar.barStyle = UIBarStyleDefault;

UIBarButtonItem *titleButton= [[UIBarButtonItem alloc] initWithTitle:@"title" style:UIBarButtonItemStylePlaintarget: nil action: nil];

UIBarButtonItem *rightButton= [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target: self action: @selector(done)];

UIBarButtonItem *leftButton  =[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBorderedtarget: self action: @selector(docancel)];

UIBarButtonItem *fixedButton  =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpacetarget: nil action: nil];

NSArray *array = [[NSArray alloc] initWithObjects:leftButton,fixedButton, titleButton,fixedButton, rightButton, nil];

[toolBar setItems: array];

[titleButton release];

[leftButton  release];

[rightButton release];

[fixedButton release];

[array       release];

[self addSubview:toolBar];

selectedStr = [[NSString alloc] init];

pickerArr = [[NSArray alloc] initWithObjects:@"10",@"20",@"30",@"40",nil];

picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, 768, 216)];

[picker setBackgroundColor:[UIColor grayColor]];

picker.showsSelectionIndicator = YES;

picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;

picker.delegate = self;

[self addSubview:picker];

}

return self;

}

-(void)viewOpen{

//[tblView reloadData];

isOpen = YES;

[UIView beginAnimations:nil context:nil];

[UIView setAnimationCurve:UIViewAnimationCurveLinear];

//[UIView setAnimationTransition:UIViewAnimationTransitionCurlUpforView:self cache:NO];

[UIView setAnimationDuration:0.4];

[self setFrame:openView];

[UIView commitAnimations];

}

-(void)viewClose{

isOpen = NO;

[UIView beginAnimations:nil context:nil];

[UIView setAnimationCurve:UIViewAnimationCurveLinear];

[UIView setAnimationDuration:0.4];

[self setFrame:closeView];

[UIView commitAnimations];

}

#pragma mark -

#pragma mark Picker Data SourceMethods

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

return 1;

}

-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component

{

return 4;

}

#pragma mark Picker DelegateMethods

- (NSString *)pickerView:(UIPickerView *)pickerViewtitleForRow:(NSInteger)row forComponent:(NSInteger)component

{

return [self.pickerArr objectAtIndex:row];

}

- (void)pickerView:(UIPickerView *)pickerViewdidSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

//[selfdismissWithClickedButtonIndex:row animated:YES];

//[self setNeedsDisplay];

//selectedPicker = [pickerArrobjectAtIndex:row];

//NSLog(@"select:%@",selectedPicker);

selectedStr = [pickerArr objectAtIndex:row];

NSLog(@"str:%@",selectedStr);

NSNotificationCenter *notificationCenter= [NSNotificationCenter defaultCenter];

NSNotification *notification= [NSNotification notificationWithName:@"refresh"object:nil];

[notificationCenter postNotification:notification];

}

-(CGFloat)pickerView:(UIPickerView *)pickerViewwidthForComponent:(NSInteger)component

{

return 768;

}

-(CGFloat)pickerView:(UIPickerView *)pickerViewrowHeightForComponent:(NSInteger)component

{

return 40;

}

-(void)done{

isOpen = NO;

[UIView beginAnimations:nil context:nil];

[UIView setAnimationCurve:UIViewAnimationCurveLinear];

[UIView setAnimationDuration:0.4];

[self setFrame:closeView];

[UIView commitAnimations];

//[selfdismissWithClickedButtonIndex:0 animated:YES];

}

- (void)cancle{

[self dismissWithClickedButtonIndex:0 animated:YES];

}

- (void)dealloc {

[selectedStr release];

[pickerArr release];

[toolBar release];

[picker release];

[super dealloc];

}

@end

pickerTestViewController.h文件

#import <UIKit/UIKit.h>

#import "pickerv.h"

#import <QuartzCore/QuartzCore.h>

@interface pickerTestViewController :UIViewController <UIActionSheetDelegate>{

UIButton *btn;

pickerv *chooseView;

}

@property (nonatomic, retain) IBOutlet UIButton*btn;

@property (nonatomic, retain)pickerv *chooseView;

-(IBAction)addpicker;

-(IBAction)addview;

@end

pickerTestViewController.m文件

#import "pickerTestViewController.h"

#import "customSheet.h"

@implementation pickerTestViewController

@synthesize btn,chooseView;

- (void)viewDidLoad {

//[super viewDidLoad];

//UIActionSheet *actionsheet=[[UIActionSheet alloc] initWithTitle:@"" delegate:selfcancelButtonTitle:@"取消" destructiveButtonTitle:nil

//   otherButtonTitles:@"选择此用户",@"删除此用户",nil];

//[actionsheetshowInView:self.view];

//[actionsheetshowFromRect:self.view.bounds inView:self.view animated:YES];

[self.view setBackgroundColor:[UIColor grayColor]];

chooseView = [[pickerv alloc] initWithFrame:CGRectMake(0,1004, 768, 0)];

[self.view addSubview:chooseView];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh)name:@"refresh" object:nil];

}

- (void)refresh{

btn.titleLabel.text= chooseView.selectedStr;

}

-(IBAction)addpicker{

//customSheet *sheet =[[customSheet alloc] initWithHeight:500];

//CGRect sheetRect =CGRectMake(0, 0, 768, 500) ;

//[sheetshowFromRect:self.view.bounds inView:self.view animated:YES];

customSheet* sheet =[[customSheet alloc] initWithHeight:284.0fWithSheetTitle:@"MyActionSheet"];

//[sheet showInView:self.view];

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0,50,320, 50)];

label.text = @"在这你想干啥就干啥";

label.backgroundColor =[UIColor clearColor];

label.textAlignment = UITextAlignmentCenter;

[sheet.view addSubview:label];

[sheet showFromRect:self.btn.bounds inView:self.view animated:YES];

[sheet release];

}

-(IBAction)addview{

[chooseView viewOpen];

//btn.titleLabel.text = chooseView.selectedStr;

}

// Override to allow orientationsother than the default portrait orientation.

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

return YES;

}

- (void)didReceiveMemoryWarning {

// Releases the view if itdoesn't have a superview.

[super didReceiveMemoryWarning];

// Release any cached data,images, etc that aren't in use.

}

- (void)viewDidUnload {

// Release any retained subviewsof the main view.

// e.g. self.myOutlet = nil;

}

- (void)dealloc {

[chooseView release];

[btn release];

[super dealloc];

}

@end

实现的功能:

[ 此帖被haoxue在2012-02-2001:26重新编辑 ]

图片:pickerview.png

iphone自定义控件,通讯录,网络,电子书,控件特效 等源码

part 1--入门:

1. xcode 版本下载 以及 iphone sdk 下载:

最新版本在此下载:

http://developer.apple.com/devcenter/ios/index.action

其他版本请看

http://connect.apple.com/cgi-bin... 1.0.1.1.0.3.3.3.3.1

2. 入门教程:

http://www.devdiv.com/thread-46499-1-1.html

part 2--代码、例程:

1. iphone编码转换方法:

http://www.devdiv.com/thread-70549-1-1.html

2. 自定义控件总结及常见页面效果:

http://www.devdiv.com/thread-63456-1-1.html

3. 通过custom url scheme启动应用程序:

http://www.devdiv.com/thread-30788-1-2.html

4. 歌曲剪切的代码例子

http://www.devdiv.com/thread-46712-1-1.html

5. ios电子书源码下载

http://www.devdiv.com/thread-65585-1-1.html

6. 条形码识别开源库:

http://www.devdiv.com/thread-41068-1-1.html

7. iPhone 利用CG API画一个饼图(Pie chart) :

http://www.devdiv.com/thread-38136-1-1.html

8. 从图片中的一点取色

http://www.devdiv.com/thread-67521-1-1.html

9. 两种自定义tabbar的方法

http://www.devdiv.com/thread-63143-1-1.html

10. cocos2d帧动画代码共享:

http://www.devdiv.com/thread-69243-1-1.html

11. UILocalNotification实现本地的闹钟提醒的方法

http://www.devdiv.com/thread-69786-1-1.html

12. 导航答的颜色设置

http://www.devdiv.com/thread-69792-1-1.html

13. IOS开发中常量的处理

http://www.devdiv.com/thread-69949-1-1.html

14. 使用定制的NSDictionary的方法,对NSArray进行排序

http://www.devdiv.com/thread-69948-1-1.html

15. UIImageView实现图片幻灯片

http://www.devdiv.com/thread-69941-1-1.html

16. 短信,电话,邮件,提示框

http://www.devdiv.com/thread-69940-1-1.html

17. 自己写的使用TouchXML解析器的一个小例子,分享一下。

http://www.devdiv.com/thread-69939-1-1.html

18. 网络等待indicator的界面设置

http://www.devdiv.com/thread-69938-1-1.html

19. 看到一种一套代码,可以多个目标(iPad/iPhone),多个版本(收费版本,试用版本)的方法。

http://www.devdiv.com/thread-69937-1-1.html

20. 去掉桌面的快捷方式的图标系统自带的高光效果

http://www.devdiv.com/thread-69936-1-1.html

21. 使用quartz2D绘制阴影的代码

http://www.devdiv.com/thread-70062-1-1.html

22. 分享一个iOS上实现的RSS的例子

http://www.devdiv.com/thread-70071-1-1.html

23. 分享一个别人的柱图

http://www.devdiv.com/thread-70067-1-1.html

24. 判断UITextField的输入只为数字的方法

http://www.devdiv.com/thread-70160-1-1.html

25. UITextField控件处理键盘弹出时遮住输入框的问题

http://www.devdiv.com/thread-70159-1-1.html

26. 分享一个好的文档 Object-C的语法与Cocoa框架-作者李海峰

http://www.devdiv.com/thread-70224-1-1.html

27. iOS 使用定制的NSDictionary的方法,对NSArray进行排序

http://www.devdiv.com/thread-70325-1-1.html

28. iOS录音相关的例子

http://www.devdiv.com/thread-70462-1-1.html

29. 通过代码添加联系人到通讯录的方法

http://www.devdiv.com/thread-70461-1-1.html

30. 中文转拼音

http://www.devdiv.com/thread-70535-1-1.html

31. 分享一个ASIHttpRequest 源码

http://www.devdiv.com/thread-70536-1-1.html

32. 短信添加联系人+多行textfield效果

http://www.devdiv.com/thread-68572-1-1.html

33. 让模拟器也支持GPS定位(模拟实现)

http://www.devdiv.com/thread-70613-1-1.html

34. 分享别人的两种闹钟的实现方法

http://www.devdiv.com/thread-70616-1-1.html

35. 播放 GIF 图片的代码

http://www.devdiv.com/thread-71496-1-1.html

36. 中文拼音排序的方法和代码例子

http://www.devdiv.com/thread-71499-1-1.html

37. iPhone 和 iPad 取色程序代码下载

http://www.devdiv.com/thread-71531-1-1.html

38. 官方文档《Xcode单元测试》中文版

http://www.devdiv.com/thread-71713-1-1.html

39. 使用MessageUI发送带附加的邮件

http://www.devdiv.com/thread-71718-1-1.html

40. NSCondition , 多线程同步例子

http://www.devdiv.com/thread-71719-1-1.html

41. 用cocos2d和chipmunk的DEMO

http://www.devdiv.com/thread-71720-1-1.html

42. Unity开发者杂志下载

http://www.devdiv.com/thread-71721-1-1.html

43.  iPhone按钮特效代码及效果图

http://www.devdiv.com/thread-71723-1-1.html

44. 玻璃破碎的特效,以及实现该特效的代码

http://www.devdiv.com/thread-71799-1-1.html

45. iPhone上画面切换特效及代码

http://www.devdiv.com/thread-71943-1-1.html

46. iPhone上的图书翻页特效代码

http://www.devdiv.com/thread-71940-1-1.html

part 3--经验分享:

1. ios4多任务机制:

http://www.devdiv.com/thread-47004-1-1.html

2. iPhone的Push(推送通知)功能原理浅析

http://www.devdiv.com/thread-67433-1-1.html

3. push机制详解:

http://www.devdiv.com/thread-41489-1-1.html

4. push消息的服务器端测试程序

http://www.devdiv.com/thread-69776-1-1.html

5.  push消息的服务端和客户端例子,测试通过的。

http://www.devdiv.com/thread-70070-1-1.html

6. iphone分区与目录结构:

http://www.devdiv.com/thread-31598-1-2.html

7. iPhone 路径大全:

http://www.devdiv.com/thread-31613-1-1.html

8. iPhone用户、用户组、权限解惑:

http://www.devdiv.com/thread-31617-1-1.html

9. ios系统架构:

http://www.devdiv.com/thread-30861-1-2.html

10. 上传一个老外的截屏工具

http://www.devdiv.com/thread-70152-1-1.html

part 4--教程:

1. Obj-C袖珍參考手冊(chm) :

http://www.devdiv.com/thread-30339-1-1.html

2. Xcode_cn开发员入门导引,挺不错的入门资料!

http://www.devdiv.com/thread-49926-1-1.html

3. iPhone开发基础教程(前12章)

http://www.devdiv.com/thread-65932-1-1.html

4. objective-c例程系列:

http://www.devdiv.com/forum.php? ...ypeid&typeid=32

5. 电子书推荐:

http://www.devdiv.com/thread-64361-1-1.html

6. 分享一个UIWebView的使用的文档,希望对大家有用

http://www.devdiv.com/thread-69795-1-1.html

获取手机号码,和IMEI  

获取本地iphone手机号码

[[NSUserDefaultsstandardUserDefaults] valueForKey:@"SBFormattedPhoneNumber"];

获取手机的imei

#import"Message/NetworkController.h"

NetworkController*ntc=[[NetworkController sharedInstance] autorelease];

NSString *imeistring= [ntc IMEI];

imeistring就是获取的imei。IMEI(International Mobile Equipment Identity)是国际移动设备身份码的缩写,

国际移动装备辨识码,是由15位数字组成的"电子串号",它与每台手机一一对应,而且该码是全世界唯一的。

UIActivityIndicatorView的两种形式 

用法一:只显示不停旋转的进度滚轮指示器。

//显示进度滚轮指示器

-(void)showWaiting {

progressInd=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:

UIActivityIndicatorViewStyleWhiteLarge];

progressInd.center=CGPointMake(self.view.center.x,240);

[self.navigationController.view addSubview:progressInd];

[progressInd startAnimating];

}

//消除滚动轮指示器

-(void)hideWaiting

{

[progressInd stopAnimating];

}

用法二:带有半透明背景的进度轮指示器。

//显示进度滚轮指示器

-(void)showWaiting:(UIView *)parent{

int width= 32, height = 32;

CGRect frame =CGRectMake(100, 200, 110, 70);//[parent frame]; //[[UIScreen mainScreen]applicationFrame];

int x= frame.size.width;

int y= frame.size.height;

frame = CGRectMake((x- width) / 2, (y - height) / 2, width, height);

UIActivityIndicatorView*progressInd = [[UIActivityIndicatorView alloc]initWithFrame:frame];

[progressInd startAnimating];

progressInd.activityIndicatorViewStyle= UIActivityIndicatorViewStyleWhiteLarge;

frame = CGRectMake((x- 70)/2, (y - height) / 2 + height, 80, 20);

UILabel *waitingLable= [[UILabel alloc] initWithFrame:frame];

waitingLable.text = @"Loading...";

waitingLable.textColor =[UIColor whiteColor];

waitingLable.font =[UIFont systemFontOfSize:15];

waitingLable.backgroundColor =[UIColor clearColor];

frame =  CGRectMake(100, 200, 110, 70);//[parent frame];

UIView *theView= [[UIView alloc] initWithFrame:frame];

theView.backgroundColor =[UIColor blackColor];

theView.alpha = 0.7;

[theView addSubview:progressInd];

[theView addSubview:waitingLable];

[progressInd release];

[waitingLable release];

[theView setTag:9999];

[parent addSubview:theView];

[theView release];

}

//消除滚动轮指示器

-(void)hideWaiting

{

[[self.view viewWithTag:9999] removeFromSuperview];

}

苹果在iPhoto中放弃使用谷歌地图

 

 据BusinessInsider报道,苹果在iOS系统的iPhoto应用中放弃了谷歌地图,而是使用OpenStreetMap Foundation提供的地图数据。这似乎标志着苹果开始放弃谷歌地图。过去几年苹果已收购了多家地图新创公司。

虽然谷歌地图非常好,但考虑到苹果和谷歌之间的冷淡关系,苹果在这样一个重要iPhone功能上依然依赖于谷歌,有些令人奇怪。另外,如果苹果完全控制iPhone上的地图,理论上可在iPhone和iPad上提供比Android设备更好的东西。此前,苹果曾在Mac版iPhoto和其他iOS应用上使用谷歌地图。OpenStreetMap周四在公司博客上称,苹果使用的OpenStreetMap数据相当旧(从2010年4月开始),预计不会有最新和最好的更新。但该公司也表示,苹果从谷歌转到OpenStreetMap让人高兴,因为在周三发布iPhoto前苹果未和他们谈过此事。地图应用程序可能是iPhone最重要的四大本地应用程序之一,但从第一代iPhone开始就一直没有大的升级。对比来看,谷歌地图的数据显然比苹果的更准确。

控制Default.png图片的显示时间

-(BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions

//等待1秒进入首页

self.timer=[NSTimerscheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];

[[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode];

do{

[[NSRunLoop currentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]];

//控制default图片显示的时间

}while(!done);

-(void)timerFired:(NSTimer*)timer{

done=YES;

}

在navigationBar上面添加多个任意控件 

在navigationBar上面添加多个任意控件

我是转的地址 给大家看看 觉得挺好

http://blog.csdn.net/ipromiseu/article/details/6080474

http://linwwwei.iteye.com/blog/1101508

获取当前的系统时间 年-月-日  小时-分钟-秒   

控制台NSLOG出的的格式  2011-09-21 07:54:46

代码如下:

NSDate * newDate =[NSDate date];

NSDateFormatter*dateformat=[[NSDateFormatter alloc] init];

[dateformatsetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *newDateOne = [dateformat stringFromDate:newDate];

[dateformatsetFormatterBehavior:NSDateFormatterFullStyle];

[dateformatsetTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSLog(@"%@",newDateOne);

ipad版实现横屏竖屏   

详解iPad横竖屏切换解决方案

 

详解iPad横竖屏切换解决方案是本文要介绍的内容,不多说,先来看内容。由于ipad的横竖屏不同,所以好的应用,

横竖屏的页面布局也不一样。那么就需要横竖屏的整体解决方案。先看一个横竖屏布局不一样的界面。

上面两张图是来自同一个界面的横竖版的截屏。可以看出,横竖版显示的内容相同,但是界面布局不同。要实现上述布局,主要是运用UIView中layoutSubviews方法。当UIView设置为自动适配屏幕时,当用户旋转设备的时候,会调用layoutSubviews方法,我们只需重写这个方法,然后判断用户屏幕的方向。在调整每个空间的位置即可。

http://mobile.51cto.com/iphone-279602.htm

读取本地文件内容

NSString*filePath=[[NSBundlemainBundle] pathForResource:@"1"ofType:@"txt"];

NSString*str=[[NSStringalloc] initWithContentsOfFile:filePath];

NSLog(@"%@",str);

如何让你的iPhone程序支持多语言环境(本地化)

我们知道,Cocoa程序是完全支持多语言的,包括iPhone中的程序。这里简单介绍一下制作多语言iPhone程序的方法,同时也是iPhone中显示中文的最好办法。

XCode中支持多语言

在项目中点右键,选择Add->NewFile

在列表中选择StringsFile

可以叫做Localizable.strings,也可以取别的名字,比如MyApp.strings

选中MyApp.string,按command+i,点击左下方的MakeFile Localizable,你会看到General中的Localizations里面已经有了English。

点击下面的AddLocalization,添加一个zh_CN(简体中文)和一个zh_TW 或者 zh_HK(繁体中文)。注意zh_Hans(简体中文)和zh_Hant(繁体中文)在Mac中可以正确识别,但是在iPhone中不能正确识别。

如果你想支持别的语言,可以添加:

日语:Japanese

德语:German

西班牙语:Spanish

法语:French

.strings文件的内容可以是标准的plist格式,也可以是旧的列表格式:

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPE plistPUBLIC "-//Apple Computer//DTD PLIST 1.0//EN""http://www.apple.com/DTDs/PropertyList-1.0.dtd">

<plistversion="1.0">

<dict>

<key>mykey</key>

<string>myvalue</string>

….

</dict>

</plist>

字符串如果要换行的话,直接按回车换行,不要写成\n这种形式。

或者直接使用旧式的列表格式:

"mykey" ="myvalue";

注意每行后面加分号。

如果你使用的是Localizable.strings,那么你在程序中可以这样获取字符串:

NSLocalizedString(@"mykey",nil)

如果你使用的是自定义名字的.strings,比如MyApp.strings,那么你在程序中可以这样获取字符串:

NSLocalizedStringFromTable(@"mykey",@"MyApp", nil)

这样即可获取到"myvalue"这个字符串,可以是任何语言。

如果你使用的是官方的iPhoneSDK,那么项目中包含这个.strings就可以直接使用了,如果你使用的是toolchain,那么需要修改一下Makefile:

增加

LANG_FILES=$(wildcard*.lproj)

LANG_FILES_ABS=$(addprefix$(SRCROOT)/,$(LANG_FILES))

RESOURCES=Resources

找到

$(APP_ABS):$(INFOPLIST_ABS)

在最后一行增加:

cp -R$(LANG_FILES_ABS) $(APP_ABS)/$(RESOURCES)

这样即可让你的iPhone程序支持多语言环境了。 当然如果你不怕麻烦,也可以每次都手工把这些.lproj目录复制到编译好的Bundle里,也是一样的。

[ 此帖被haoxue在2012-03-2023:22重新编辑 ]

图片:3292_111124102708_1.png

将自己开发的app打包成ipa装入iPhone的教程

http://www.cocoachina.com/newbie/tutorial/2010/0402/927.html

Cocoa 框架由Foundation Kit、App Kit 两部分组成,前者是基础工具库,是你必须首先要学

会的,后者主要是UI 库、高级对象等,我们这里只介绍Foundation Kit。

在Objective-C 中使用前缀可以有效的防止名称冲突。

iOS5的新功能之解析JSON   

iOS5新加了很多新功能,解析JSON也是其中的一个。

下面是我最近写的一个小DMEO。关于JSON的,现放出与大家共享。

以下代码参考VandadNahavandipoor的 《iOS 5Programming Cookbook》。

这个是保存的方法。

-(IBAction)touchWriteButton:(id)sender {

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

[dictionary setValue:@"Anthony" forKey:@"First Name"];

[dictionary setValue:@"Robbins" forKey:@"Last Name"];

[dictionary setValue:[NSNumber numberWithUnsignedInteger:51]forKey:@"Age"];

NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:

@"Anthony's Son 1",@"Anthony's Daughter 1", @"Anthony's Son 2",@"Anthony's Son 3", @"Anthony's Daughter 2", nil];

[dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];

NSError *error = nil;

NSData*jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryoptions:NSJSONWritingPrettyPrinted error:&error];

if(error) {

NSLog(@"dic->%@",error);

}

[dictionary release];

BOOLsucceed = [jsonData writeToFile:JSON_PATH atomically:YES];

if (succeed){

NSLog(@"Save succeed");

}else{

NSLog(@"Save fail");

}

}

这个是读取的方法。

-(IBAction)touchReadButton:(id)sender {

NSData*jsonData = [[NSData alloc] initWithContentsOfFile:JSON_PATH];

/* Nowtry to deserialize the JSON object into a dictionary */

NSError *error = nil;

idjsonObject = [NSJSONSerialization JSONObjectWithData:jsonDataoptions:NSJSONReadingAllowFragments error:&error];

if(jsonObject != nil && error == nil){

NSLog(@"Successfully deserialized...");

if ([jsonObject isKindOfClass:[NSDictionary class]]){

NSDictionary *deserializedDictionary = (NSDictionary*)jsonObject;

NSLog(@"Dersialized JSON Dictionary = %@",deserializedDictionary);

} else if ([jsonObject isKindOfClass:[NSArray class]]){

NSArray *deserializedArray = (NSArray *)jsonObject;

NSLog(@"Dersialized JSON Array = %@",deserializedArray);

} else {

NSLog(@"An error happened while deserializing theJSON data.");

}

}

[jsonData release];

}

此功能仅限于IOS5才能使用。他的解析效率是目前市面上最高的。iOS5系统API和5个开源库的JSON解析速度测试

XML和json都是用来保存、读取、传递数据。

用NSDateFormatter调整时间格式

在开发iOS程序时,有时候需要将时间格式调整成自己希望的格式,这个时候我们可以用NSDateFormatter类来处理。

例如:

//实例化一个NSDateFormatter对象

NSDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];

//设定时间格式,这里可以设置成自己需要的格式

[dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//用[NSDate date]可以获取系统当前时间

NSString*currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

//输出格式为:2010-10-27 10:22:13

NSLog(@”%@”,currentDateStr);

//alloc后对不使用的对象别忘了release

[dateFormatter release];

如何将本地时间转化为"指定时区"的时间

NSDateFormatter *formatter=[[NSDateFormatter alloc] init];

[formattersetDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSTimeZone* timeZone =[NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

[formattersetTimeZone:timeZone];

NSString *loctime =[formatter stringFromDate:date];

[formatter release];

----------------------------------------------------------------------------------------------------

不管用户如何设置,,均获得24小时显示(其中的HH,强制指定为24时制)

NSDateFormatter *formatter =[[NSDateFormatter alloc] init];

[formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *loctime =[formatter stringFromDate:date];

[formatter release]

Objective-c的 @property 详解

之前很多网友对教程中的Property的使用感到有些迷惑不解,搞不清楚什么时候要release,什么时候要self.xxx= nil;同时对于Objective-c的内存管理以及cocos2d的内存管理规则不够清楚。本文主要讲解objc里面@property,它是什么,它有什么用,atomic,nonatomic,readonly,readwrite,assign,retain,copy,getter,setter这些关键字有什么用,什么时候使用它们。至于Objc的内存管理和cocos2d的内存管理部分,接下来,我会翻译Ray的3篇教程,那里面再和大家详细讨论。今天我们的主要任务是搞定@property。

学过c/c++的朋友都知道,我们定义struct/class的时候,如果把访问限定符(public,protected,private)设置为public的话,那么我们是可以直接用.号来访问它内部的数据成员的。比如

//in Test.h

class Test

{

public:

int i;

float f;

};

我在main函数里面是可以通过下面的方式来使用这个类的:(注意,如果在main函数里面使用此类,除了要包含头文件以外,最重要的是记得把main.m改成main.mm,否则会报一些奇怪的错误。所以,任何时候我们使用c++,如果报奇怪的错误,那就要提醒自己是不是把相应的源文件改成.mm后缀了。其它引用此类的文件有时候也要改成.mm文件)

//in main.mm

Test test;

test.i =1;

test.f =2.4f;

NSLog(@"Test.i = %d, Test.f = %f",test.i,  test.f);

但是,在objc里面,我们能不能这样做呢?请看下面的代码:(新建一个objc类,命名为BaseClass)

//in BaseClass.h

@interface BaseClass : NSObject{

@public

NSString *_name;

}

接下来,我们在main.mm里面:

BaseClass *base= [[BaseClassalloc] init];

base.name =@"set basename";

NSLog(@"base class's name= %@", base.name);

不用等你编译,xcode4马上提示错误,请看截图:

请大家注意看出错提示“Property'nam' not found on object of type BaseClass*",意思是,BaseClass这类没有一个名为name的属性。即使我们在头文件中声明了@public,我们仍然无法在使用BaseClass的时候用.号来直接访问其数据成员。而@public,@protected和@private只会影响继承它的类的访问权限,如果你使用@private声明数据成员,那么在子类中是无法直接使用父类的私有成员的,这和c++,java是一样的。

既然有错误,那么我们就来想法解决啦,编译器说没有@property,那好,我们就定义property,请看代码:

//in BaseClass.h

@interface BaseClass :NSObject{

@public

NSString *_name;

}

@property(nonatomic,copy)NSString *name;

//in BaseClass.m

@synthesize name = _name;

现在,编译并运行,ok,很好。那你可能会问了@prperty是不是就是让”."号合法了呀?只要定义了@property就可以使用.号来访问类的数据成员了?先让我们来看下面的例子:

@interface BaseClass :NSObject{

@public

NSString *_name;

}

//@property(nonatomic,copy)NSString *name;

-(NSString*) name;

-(void)setName:(NSString*)newName;

我把@property的定义注释掉了,另外定义了两个函数,name和setName,下面请看实现文件:

//@synthesize name = _name;

-(NSString*) name{

return _name;

}

-(void) setName:(NSString*)name{

if (_name !=name) {

[_name release];

_name = [name copy];

}

}

现在,你再编译运行,一样工作的很好。why?因为我刚刚做的工作和先前声明@property所做的工作完成一样。@prperty只不过是给编译器看的一种指令,它可以编译之后为你生成相应的getter和setter方法。而且,注意看到面property(nonatomic,copy)括号里面这copy参数了吗?它所做的是就是

_name = [name copy];

如果你指定retain,或者assign,那么相应的代码分别是:

//property(retain)NSString*name;

_name = [name retain];

//property(assign)NSString*name;

_name = name;

其它讲到这里,大家也可以看出来,@property并不只是可以生成getter和setter方法,它还可以做内存管理。不过这里我暂不讨论。现在,@property大概做了件什么事,想必大家已经知道了。但是,我们程序员都有一个坎,就是自己没有完全吃透的东西,心里用起来不踏实,特别是我自己。所以,接下来,我们要详细深挖@property的每一个细节。

首先,我们看atomic与nonatomic的区别与用法,讲之前,我们先看下面这段代码:

@property(nonatomic, retain)UITextField *userName;    //1

@property(nonatomic,retain,readwrite) UITextField *userName;  //2

@property(atomic, retain)UITextField *userName;  //3

@property(retain) UITextField*userName;  //4

@property(atomic,assign) inti;         // 5

@property(atomic) int i;        //6

@property int i;              //7

请读者先停下来想一想,它们有什么区别呢?

上面的代码1和2是等价的,3和4是等价的,5,6,7是等价的。也就是说atomic是默认行为,assign是默认行为,readwrite是默认行为。但是,如果你写上@property(nontomic)NSString*name;那么将会报一个警告,如下图:

因为是非gc的对象,所以默认的assign修饰符是不行的。那么什么时候用assign、什么时候用retain和copy呢?推荐做法是NSString用copy,delegate用assign(且一定要用assign,不要问为什么,只管去用就是了,以后你会明白的),非objc数据类型,比如int,float等基本数据类型用assign(默认就是assign),而其它objc类型,比如NSArray,NSDate用retain。

在继续之前,我还想补充几个问题,就是如果我们自己定义某些变量的setter方法,但是想让编译器为我们生成getter方法,这样子可以吗?答案是当然可以。如果你自己在.m文件里面实现了setter/getter方法的话,那以翻译器就不会为你再生成相应的getter/setter了。请看下面代码:

//代码一:

@interface BaseClass :NSObject{

@public

NSString *_name;

}

@property(nonatomic,copy,readonly)NSString *name;  //这里使用的是readonly,所有会声明geter方法

-(void) setName:(NSString*)newName;

//代码二:

@interface BaseClass :NSObject{

@public

NSString *_name;

}

@property(nonatomic,copy,readonly)NSString *name;   //这里虽然声明了readonly,但是不会生成getter方法,因为你下面自己定义了getter方法。

-(NSString*) name;  //getter方法是不是只能是name呢?不一定,你打开Foundation.framework,找到UIView.h,看看里面的property就明白了)

-(void)setName:(NSString*)newName;

//代码三:

@interface BaseClass :NSObject{

@public

NSString *_name;

}

@property(nonatomic,copy,readwrite)NSString *name;  //这里编译器会我们生成了getter和setter

//代码四:

@interface BaseClass : NSObject{

@public

NSString *_name;

}

@property(nonatomic,copy)NSString *name;  //因为readwrite是默认行为,所以同代码三

上面四段代码是等价的,接下来,请看下面四段代码:

//代码一:

@synthesize name = _name; //这句话,编译器发现你没有定义任何getter和setter,所以会同时会你生成getter和setter

//代码二:

@synthesize name = _name; //因为你定义了name,也就是getter方法,所以编译器只会为生成setter方法,也就是setName方法。

-(NSString*) name{

NSLog(@"name");

return _name;

}

//代码三:

@synthesize name = _name;  //这里因为你定义了setter方法,所以编译器只会为你生成getter方法

-(void) setName:(NSString*)name{

NSLog(@"setName");

if (_name !=name) {

[_name release];

_name = [name copy];

}

}

//代码四:

@synthesize name = _name; //这里你自己定义了getter和setter,这句话没用了,你可以注释掉。

-(NSString*) name{

NSLog(@"name");

return _name;

}

-(void) setName:(NSString*)name{

NSLog(@"setName");

if (_name !=name) {

[_name release];

_name = [name copy];

}

}

上面这四段代码也是等价的。看到这里,大家对Property的作用相信会有更加进一步的理解了吧。但是,你必须小心,你如果使用了Property,而且你自己又重写了setter/getter的话,你需要清楚的明白,你究竟干了些什么事。别写出下面的代码,虽然是合法的,但是会误导别人:

//BaseClass.h

@interface BaseClass :NSObject{

@public

NSArray *_names;

}

@property(nonatomic,assgin,readonly)NSArray *names;  //注意这里是assign

-(void)setNames:(NSArray*)names;

//BaseClass.m

@implementation BaseClass

@synthesize names = _names;

-(NSArray*) names{

NSLog(@"names");

return _names;

}

-(void)setNames:(NSArray*)names{

NSLog(@"setNames");

if (_name !=name) {

[_name release];

_name = [name retain];  //你retain,但是你不覆盖这个方法,那么编译器会生成setNames方法,里面肯定是用的assign

}

}

当别人使用@property来做内存管理的时候就会有问题了。总结一下,如果你自己实现了getter和setter的话,atomic/nonatomic/retain/assign/copy这些只是给编译的建议,编译会首先会到你的代码里面去找,如果你定义了相应的getter和setter的话,那么好,用你的。如果没有,编译器就会根据atomic/nonatomic/retain/assign/copy这其中你指定的某几个规则去生成相应的getter和setter。

好了,说了这么多,回到我们的正题吧。atomic和nonatomic的作用与区别:

如果你用@synthesize去让编译器生成代码,那么atomic和nonatomic生成的代码是不一样的。如果使用atomic,如其名,它会保证每次getter和setter的操作都会正确的执行完毕,而不用担心其它线程在你get的时候set,可以说保证了某种程度上的线程安全。但是,我上网查了资料,仅仅靠atomic来保证线程安全是很天真的。要写出线程安全的代码,还需要有同步和互斥机制。

而nonatomic就没有类似的“线程安全”(我这里加引号是指某种程度的线程安全)保证了。因此,很明显,nonatomic比atomic速度要快。这也是为什么,我们基本上所有用property的地方,都用的是nonatomic了。

还有一点,可能有读者经常看到,在我的教程的dealloc函数里面有这样的代码:self.xxx= nil;看到这里,现在你们明白这样写有什么用了吧?它等价于[xxx release];  xxx = [nil retain];(---如果你的property(nonatomic,retian)xxx,那么就会这样,如果不是,就对号入座吧)。

因为nil可以给它发送任何消息,而不会出错。为什么release掉了还要赋值为nil呢?大家用c的时候,都有这样的编码习惯吧。

int* arr = newint[10];    然后不用的时候,deletearr; arr = NULL;  在objc里面可以用一句话self.arr = nil;搞定。

讲了这么多,,如果大家还有什么问题,欢迎在下方留言,我有时间一定会忙回复你的。一直看我文章的朋友们,如果知道答案也帮忙回答一下哈,先谢谢你们啦!

浅谈Objective-C 下对象的初始化

众所周知,Objective-C是一门面向对象的语言,一般情况下,我们在Objective-C中定义一个类时,总要提供一个初始化方法,一般大家都是这样写的:

[color=initial!important][table=0px !important][tr][td]1[/td][td]- (MyClass*)init[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]2[/td][td]{[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]3[/td][td] self = [superinit]; [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]4[/td][td] if (self){[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]5[/td][td] //执行一些资源、变量的初始化工作[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]6[/td][td] }[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]7[/td][td]return self;[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]8[/td][td]}[/td][/tr][/table]

这样一段简单的代码,却有很多可以思考的问题:

1、为什么要通过[super init]来调用父类的初始化方法,父类的初始化方法里又执行了什么东西?

首先,我们知道对象继承的概念,一个子类从父类继承,那么也要实现父类的所有功能,这就是is-a的关系,比如说狗是哺乳动物,那么狗必定具有哺乳动物的特征和功能。所以在子类的初始化方法中,必须首先调用父类的初始化方法,以实现父类相关资源的初始化。例如我们在初始化狗这一对象时,必须先初始化哺乳动物这一对象,并把结果赋予狗,以使狗满足属于哺乳动物这一特征。

典型的,在iOS下,所有的类都继承于NSObject,而NSObject的init方法很简单,就是return self。当父类的初始化完成之后,即self不为nil的情况下,就可以开始做子类的初始化了。

2、是否一定要提供初始化方法,是否一定要使用init作为初始化方法?

我们在Objective-C中创建一个对象通常使用

[color=initial!important][table=0px !important][tr][td]1[/td][td]MyClass *newclass =[[MyClass alloc] init];[/td][/tr][/table]     或者

[color=initial!important][table=0px !important][tr][td] [/td][td]

MyClass *newclass =[Myclass new];  [/td][/tr][/table]

new方法是NSObject对象的一个静态方法,根据apple的文档,该方法实际上就是alloc和init方法的组合,实际上二者是一样的,但 apple还是推荐我们使用第一种方法,为什么呢?因为使用第一种方法,你可以使用自己定义的init方法来做一些初始化,当然,如果子类没有提供 init方法,自然调用的就是父类的init方法了。所以说,从安全性的角度来收,作为开发者我们在对象使用之前是一定要对对象进行初始化的,因此在定义类的时候一定要提供初始化方法。但是否一定要使用init作为方法名呢?答案是不一定。使用init作为方法名只是你重写了NSObject的init方法而已,如果你自己重新定义一个初始化方法,也是完全可以的,只要你在使用的时候记得调用新定义的初始化方法就可以了。

但是,这种方法从设计角度来看我觉得是不可取的。在可复用性方面会比较差,如果确有必要定义一些接受不同参数的初始化方法,我的建议是,先定义一个init的公用方法,再到其他方法中调用它,如:

[color=initial!important][color=initial !important][color=initial !important][table=0px!important][tr][td]01[/td][td]- (id)init[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]02[/td][td]{[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]03[/td][td] self = [super init]; [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]04[/td][td] if (self){[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]05[/td][td]  [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]06[/td][td] }[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]07[/td][td]return self;[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]08[/td][td]}[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]09[/td][td] [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]10[/td][td]-(id)initWithString:(NSString *)aString[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]11[/td][td]{[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]12[/td][td] [selfinit];[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]13[/td][td] self.name =aString;  [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]14[/td][td]}[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]15[/td][td]  [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]16[/td][td]-(id)initWithImage:(UIImage *)aImage[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]17[/td][td]{[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]18[/td][td] [selfinit];[/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]19[/td][td] self.image =aImage;  [/td][/tr][/table]

[color=initial!important][table=0px !important][tr][td]20[/td][td]}[/td][/tr][/table]

补充:

在面向对象编程中,如果编写一个类而没有包含构造函数,这个类仍能编译并且完全可以正常使用。如果类没有提供显式的构造函数,编译器会提供一个默认的构造函数给你。除了创建对象本身,默认构造函数的唯一工作就是调用其超类的构造函数。在很多情况下,这个超类是语言框架的一部分,如java中的Object类,objective-c 中的NSObject类。

不论是何种情况,在类中至少包含一个构造函数是一种很好的编程实践,如果类中有属性,好的实践往往是初始化这些属性。

——以上摘自《TheObject-Oriented Thought Process》 byMatt Weisfeld

IOS开发之百度地图API应用

目前我们在做IOS开发中绝大多数用的是GoogleMap地图,IOS本身自带的也是googleMap,但是如果我们希望在地图上实时显示路况信息等部分功能,googlemap则没有,所以有时候我们可以应用百度地图做应用程序。下面我简单介绍一下BMapKit的应用:

一:首先我们有一点与用googlemap开发的不同,需要创建BMKMapManager管理应用程序的map,如果没有这个类,地图则不能够显示。

下面红色的字体是自己在百度官方申请的地图api——key;

BMKMapManager *_mapManager = [[BMKMapManager alloc] init];

BOOL ret = [_mapManagerstart:@"C3252C69EDB6D21A10B3FC9657FD1DDC7E0000**"generalDelegate:self];

if (!ret) {

NSLog(@"managerstart failed!");

}

二:在view中添加BMKMapView,同时设置BMKMapViewDelegate,添加annotation(记录兴趣

点,BMKAnnotation),同时每个兴趣点可以设置其title(设置annotation的标题),以及subtitle(子标题)。

@interface MapBaiDu: UIViewController <BMKMapViewDelegate> {  }

@property (nonatomic, strong) BMKMapView *_mapView;

@end

- (void)viewDidLoad {

_mapView =[[BMKMapViewalloc] initWithFrame:CGRectMake(0, 39, 320, 377)];    //创建MKMapView

[self.view addSubview:_mapView];

[_mapView release];

_mapView.delegate = self;                           //设置代理

_mapView.showsUserLocation = YES;               //设置为可以显示用户位置

CLLocationCoordinate2D coordinate;                 //设定经纬度

coordinate.latitude = 40.027283;        //纬度

coordinate.longitude = 116.313217;      //经度

BMKCoordinateRegion viewRegion= BMKCoordinateRegionMake(coordinate, BMKCoordinateSpanMake(1.0,1.0));

BMKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];

[_mapView setRegion:adjustedRegion animated:YES];

}

上面最后一行 :设置当前地图的经纬度范围,设定的该范围可能会被调整为适合地图窗口显示的范围。region是BMKMapView的一个属性,类型BMKCoordinateRegion ,这行的意思是创建一个以coordinate为中心,上下左右个0.5个经(纬)度。但是这时我们需要注意一个问题就是,创建的区域是一个正方形,并不符合我们所需要的BMKMapView比例;之后用方法regionThatFits调整显示范围。

///表示一个经纬度区域

typedefstruct {

CLLocationCoordinate2D center; ///< 中心点经纬度坐标

BMKCoordinateSpan span; ///< 经纬度范围

}BMKCoordinateRegion;

///表示一个经纬度范围

typedefstruct {

CLLocationDegrees latitudeDelta; ///< 纬度范围

CLLocationDegrees longitudeDelta; ///< 经度范围

} BMKCoordinateSpan;

三:下面我们简单说一下delegate

1:地图区域改变时候调用函数:

-(void)mapView:(BMKMapView *)mapViewregionWillChangeAnimated:(BOOL)animated;

-(void)mapView:(BMKMapView *)mapViewregionDidChangeAnimated:(BOOL)animated;

2:annotation

*根据anntation生成对应的View

-(BMKAnnotationView *)mapView:(BMKMapView *)mapViewviewForAnnotation:(id<BMKAnnotation>)annotation;

*当mapView新添加annotationviews时,调用此接口

-(void)mapView:(BMKMapView *)mapViewdidAddAnnotationViews:(NSArray *)views;

*当选中一个annotation views时,调用此接口

-(void)mapView:(BMKMapView *)mapViewdidSelectAnnotationView:(BMKAnnotationView *)view;

*当取消选中一个annotation views时,调用此接口

-(void)mapView:(BMKMapView *)mapViewdidDeselectAnnotationView:(BMKAnnotationView *)view;

而annotation分为两部分:BMKAnotation该类为标注点的protocol,提供了标注类的基本信息函数,title和subtitle分别是标题和子标题;同时可以设置标注的左边,在拖曳时候会被调用setCoordinate;

BMKAnnotationView为标注点显示视图类,该类继承UIView,可以设置此view显示的图像,可以设置centerOffset(中心的位置,正的偏移使view超右下方移动,负的朝右上方移动,单位为像素),还可以设置calloutOffset改变淡出的气泡位置(正的偏移使view超右下方移动,负的朝左上方移动,单位是像素)。还可以设置其触摸事件,默认情况下为YES,可以选中,也可以是enabled= NO。其他的属性还有:selected,canShowCallout,leftCalloutAccessoryView,rightCalloutAccessoryView。等等

四:当地图view定位时调用函数:

*当取消选中一个annotation views时,调用此接口

-(void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view;

*在地图View将要启动定位时,会调用此函数

-(void)mapViewWillStartLocatingUser:(BMKMapView *)mapView;

*在地图View停止定位后,会调用此函数

-(void)mapViewDidStopLocatingUser:(BMKMapView *)mapView;

*定位失败后,会调用此函数

-(void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error;

*用户位置更新后,会调用此函数

-(void)mapView:(BMKMapView *)mapViewdidUpdateUserLocation:(BMKUserLocation *)userLocation;

五:当有overlay(阴影标示某一个区域)生成或者新添加的时候调用此接口

*根据overlay生成对应的View

-(BMKOverlayView *)mapView:(BMKMapView *)mapViewviewForOverlay:(id <BMKOverlay>)overlay;

*当mapView新添加overlayviews时,调用此接口

-(void)mapView:(BMKMapView *)mapViewdidAddOverlayViews:(NSArray *)overlayViews;

六:

当点击

annotation view

弹出的泡泡时,调用此接口

*当点击annotation view弹出的泡泡时,调用此接口

- (void)mapView:(BMKMapView *)mapViewannotationViewForBubble:(BMKAnnotationView *)view;

九:annotation view有许多不同的状态,在不同状态的时候我们都可以设置不同的操作,拖动annotation view时view的状态变化

-(void)mapView:(BMKMapView *)mapViewannotationView:(BMKAnnotationView *)view didChangeDragState:(BMKAnnotationViewDragState)newState

fromOldState:(BMKAnnotationViewDragState)oldState;

enum {

BMKAnnotationViewDragStateNone = 0,      ///< 静止状态.

BMKAnnotationViewDragStateStarting,      ///< 开始拖动

BMKAnnotationViewDragStateDragging,      ///< 拖动中

BMKAnnotationViewDragStateCanceling,     ///< 取消拖动

BMKAnnotationViewDragStateEnding         ///< 拖动结束

};

typedef NSUInteger BMKAnnotationViewDragState;

使用Xcode4 发布程序教程

在新建程序时需要输入buildid,xcode4比较人性化的一方面,按需要输入。

之后进入项目中,按图所示,选择项目配置,部署sdk(注意和basesdk的区别),在下面可以复制出来几个配置来实现不同的需求。一般复制一个release来做发布配置就可以了。下面的本地化不多说了。

接着选择下面的target配置,这里需要做的就是配置idertifier

在上面的标签选info,这里需要改的有bundle display name及bundle name(显示名),excutable file我一般默认。icon file为图标文件名(注意和iconfiles的区别)。bundle identifier就是之前第1步和第3步的id,以及下面的版本号及所有的info.plistkey都在这设置。

上面的标签选buildsettings,找到code signing分组,如图设置签名,如果之前在第2步那复制出多个,这也会显示多个。

xcode4的左上角下拉列表,选择ios device,同时进入edit scheme

如图所示选择配置,你是要编译debug还是release.如果嫌麻烦,可以在左侧分开修改,至于切换是在xcode左上角的RUN按钮上一直按左键。

基于官方UIImagePicker的图片多选

正好有个项目用到类似的功能,先搜索了一圈,找到了ELCImagePicker的解决方案,并且多数提此类问题,最终得到的回答都是此方案。

结果发现有一个硬伤,就是基于ALAssertLibrary,会在第一次使用此功能时弹出提醒用户打开定位的提示,这个提示完全不可控,用户如果选择禁止访问,就歇菜了,下次打开不会再有提示,直接报错。

必须手动进入设置->定位中开启。且打开特定设置面板的API需要IOS5SDK。

使用方法如下:

MHImagePickerMutilSelector*imagePickerMutilSelector=[MHImagePickerMutilSelector standardSelector];//自动释放

imagePickerMutilSelector.delegate=self;//设置代理

UIImagePickerController*picker=[[UIImagePickerController alloc] init];

picker.delegate=imagePickerMutilSelector;//将UIImagePicker的代理指向到imagePickerMutilSelector

[picker setAllowsEditing:NO];

picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;

picker.modalTransitionStyle=UIModalTransitionStyleCoverVertical;

picker.navigationController.delegate=imagePickerMutilSelector;//将UIImagePicker的导航代理指向到imagePickerMutilSelector

imagePickerMutilSelector.imagePicker=picker;//使imagePickerMutilSelector得知其控制的UIImagePicker实例,为释放时需要。

[selfpresentModalViewController:picker animated:YES];

[picker release];

就一个代理的方法,获得多选的图片数据数组

-(void)imagePickerMutilSelectorDidGetImages:(NSArray*)imageArray

{

importItems=[[NSMutableArrayalloc]initWithArray:imageArray copyItems:YES];

}

36.        MHImagePickerMutilSelector.zip

图片:4064_120810085853_1.jpg

实现弹出软键盘后不遮挡文本框,自动调整屏幕高度方法

第一步:在头文件加入<UITextFieldDelegate>协议,并定义成员变量

int keyBoardMargin_; //记录上一次移动的间距,用户离开文本时恢复视图高度

第二步:在xib文件设置文本框的delegate与file'owner连接,或者在m文件用代码实现代理的连接(文本控件.delegate=self)

int keyBoardMargin_; //记录上一次移动的间距,用户离开文本时恢复视图高度

第三步:m文件中加入以下方法

#pragma mark - 处理文本位置方法

- (void)moveView:(UITextField *)textField leaveView:(BOOL)leave

{

float screenHeight = 480; //屏幕尺寸,如果屏幕允许旋转,可根据旋转动态调整

float keyboardHeight = 216; //键盘尺寸,如果屏幕允许旋转,可根据旋转动态调整

float statusBarHeight,NavBarHeight,tableCellHeight,textFieldOriginY,textFieldFromButtomHeigth;

int margin;

statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height; //屏幕状态栏高度

NavBarHeight = self.navigationController.navigationBar.frame.size.height; //获取导航栏高度

UITableViewCell *tableViewCell=(UITableViewCell *)textField.superview;

tableCellHeight = tableViewCell.frame.size.height; //获取单元格高度

CGRect fieldFrame=[self.view convertRect:textField.frame fromView:tableViewCell];

textFieldOriginY = fieldFrame.origin.y; //获取文本框相对本视图的y轴位置。

NSLog(@"textFieldOriginY=%f",textFieldOriginY);

NSLog(@"tableCellHeight=%f",tableCellHeight);

NSLog(@"NavBarHeight=%f",NavBarHeight);

NSLog(@"statusBarHeight=%f",statusBarHeight);

//计算文本框到屏幕底部的高度(屏幕高度-顶部状态栏高度-导航栏高度-文本框的的相对y轴位置-单元格高度)

textFieldFromButtomHeigth = screenHeight - statusBarHeight - NavBarHeight - textFieldOriginY - tableCellHeight;

if(!leave) {

if(textFieldFromButtomHeigth < keyboardHeight) { //如果文本框到屏幕底部的高度 < 键盘高度

margin = keyboardHeight - textFieldFromButtomHeigth; // 则计算差距

keyBoardMargin_ = margin; //keyBoardMargin_ 为成员变量,记录上一次移动的间距,用户离开文本时恢复视图高度

} else {

margin= 0;

keyBoardMargin_ = 0;

}

}

NSLog(@"keyBoardMargin_=%d",keyBoardMargin_);

c*****t float movementDuration = 0.3f; // 动画时间

int movement = (leave ? keyBoardMargin_ : -margin); //进入时根据差距移动视图,离开时恢复之前的高度

[UIView beginAnimati*****: @"textFieldAnim" context: nil]; //添加动画

[UIView setAnimationBeginsFromCurrentState: YES];

[UIView setAnimationDuration: movementDuration];

self.view.frame = CGRectOffset(self.view.frame, 0, movement);

[UIView commitAnimati*****];

}

第四步:m文件中加入以下协议方法

- (void)textFieldDidBeginEditing:(UITextField *)textField

{

[self moveView:textField leaveView:NO];

}

- (void)textFieldDidEndEditing:(UITextField *)textField;

{

[self moveView:textField leaveView:YES];

}

注:margin = keyboardHeight - textFieldFromButtomHeigth; // 则计算差距

这里应该写

margin = keyboardHeigh;  //也就是view向上推一个键盘的高度

如果按照你写的计算差距,如果文本框刚好在键盘的高度内,会导致页面推到上面。

我的*****:213681048

[ 此帖被haoxue在2012-08-24 00:42重新编辑 ]

附件:  UITextView.zip (99 K) 下载次数:10

百度地图自定义弹出气泡的实现代码   

最近项目中要加入地图搜索功能,目前选择的是百度地图。

官方指南:http://dev.baidu.com/wiki/imap/index.php?title=iOS平台/开发指南

但是百度地图默认的弹出气泡只能显示两行文字,所以需要自定义实现。

网上搜索没找到现成代码,只好自己动手实现,现将代码分享,希望帮到需要的朋友。

其间参考了论坛中几个很有用的帖子,在此一并感谢。

注:必须在Xcode4下编译项目,项目中用的是真机的sdk,只能在设备上运行。如果想在模拟器中运行,请自行去官网下载对应库文件。

需要申请百度地图API Key,填在AppDelegate.m中相应位置,例如

[_mapManager start:@"此处填写自己的API Key" generalDelegate:nil];  BMKBubbleDemo.zip

图片:19_83747_8c218895d371711.png

下拉刷新上拉加载的TableView

1.支持手动控制出现下拉刷新界面,调用launchRefreshing方法即可

2.支持只启用下拉刷新或者同时启用上拉下拉,需要禁用上拉加载设置headerOnly = YES

3.支持刷新或者加载完后顶部出现文字提示消息,如“已全部加载完”

需要消息提示调用tableViewDidFinishedLoadingWithMessage:(NSString *)msg,不需要则调用tableViewDidFinishedLoadingWithMessage即可

附件:  PullingTableDemo.zip (69 K) 下载次数:10

共享个对做天气有点帮助的plist

之前做个要用中国气象局api的天气报告view,接口要用城市编号做查询条件

被要求要将数据存进本地,于是就有了这份十分呕血的plist

内有两份plist,一份是纪录省和市的,用来做pickerview的选择挺方便的

另外一份就是城市和对应编号的键值对plist啦 ,另外附上中国气象局的api

http://www.weather.com.cn/data/sk/101010100.html

http://www.weather.com.cn/data/cityinfo/101010100.html

http://m.weather.com.cn/data/101010100.html

后面那个101010100就是北京的城市编号啦,根据不同编号就能查询不同城市的天气状况

附件:  weather的plist.zip (12 K) 下载次数:9

OpenFlow  循环滚动 简单详细代码及说明  215楼

附件:  MyFlow 2.zip (238 K) 下载次数:13

录音并发送的demo

我的*****:213681048

附件:  recordAudioAndSend.zip (77 K) 下载次数:9

 

支持多路mp3声音播放的完整演示工程

支持多路mp3声音播放的完整演示工程 下载

这个代码支持多路mp3\wav的同时播放, 经过测试 在模拟器上\真机iphone上\ipod touch上 (包括2.0到2.2固件) 都能正确播放

附件:  hssSoundEngineDemo.zip (619 K) 下载次数:9

如何在iPhone程序读取数据时显示进度窗

以下代码参考了MobileRss。

定义头文件:

37.        #import"uikit/UIProgressHUD.h"

38.

39.        @interface EyeCandy : UIApplication {

40.         UIProgressHUD *progress;

41.        }

42.

43.        - (void) showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)vwithRect:(struct CGRect)rect;

44.        - (void) hideProgressHUD;

45.

46.        @end

上面的引号要改成<>。

13.        import "EyeCandy.h"

14.

15.        @implementation EyeCandy

16.        - (void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)vwithRect:(struct CGRect)rect

17.        {

18.         progress = [[UIProgressHUD alloc] initWithWindow: w];

19.         [progresssetText: label];

20.         [progress drawRect: rect];

21.         [progressshow: YES];

22.

23.         [v addSubview:progress];

24.        }

25.

26.        - (void)hideProgressHUD

27.        {

28.         [progressshow: NO];

29.         [progress removeFromSuperview];

30.        }

31.

32.        @end

使用下面代码调用:

11.        //Setup Eye Candy View

12.        _eyeCandy = [[[EyeCandy alloc] init] retain];

13.

14.        //Call loading display

15.        [_eyeCandyshowProgressHUD:@"Loading…" withWindow:window withView:mainViewwithRect:CGRectMake(0.0f, 100.0f, 320.0f, 50.0f)];

16.

17.        //When finished for hiding the "loading text"

[_eyeCandy hideProgressHUD];

如何在UIAlertView中显示进度条

在一个iPhone程序中,我要在后台做大量的数据处理,希望在界面上显示一个进度条(Progress Bar)使得用户了解处理进度。这个进度条应该是在一个模态的窗口中,使界面上其他控件无法被操作。怎么用最简单的方法来实现这个功能?

UIAlertView

是一个现成的模态窗口,如果能把进度条嵌入到它里面就好了。

我们知道,如果要显示一个alert窗口(比如用来显示错误或警告信息、询问用户是否确认某操作等等),只要简单地创建一个UIAlertView对象,再调用其show方法即可。示意代码如下:

UIAlertView[backcolor=transparent]* alertView [backcolor=transparent]= [backcolor=transparent][[backcolor=transparent][[backcolor=transparent][UIAlertViewalloc[backcolor=transparent]] initWithTitle[backcolor=transparent]:[backcolor=transparent]@[backcolor=transparent]"Title"

message[backcolor=transparent]:[backcolor=transparent]@[backcolor=transparent]"Message"

delegate[backcolor=transparent]:[backcolor=transparent]nil

cancelButtonTitle[backcolor=transparent]:[backcolor=transparent]@[backcolor=transparent]"OK"

otherButtonTitles[backcolor=transparent]:[backcolor=transparent]nil[backcolor=transparent]]

autorelease[backcolor=transparent]];

[backcolor=transparent][alertViewshow[backcolor=transparent]];

如果要添加一个进度条,只要先创建并设置好一个UIProgressView的实例,再利用addSubbiew方法添加到alertView中即可。

在实际应用中,我可能需要在类中保存进度条的对象实例,以便更新其状态,因此先在自己的ViewController类中添加成员变量:

[backcolor=transparent]// MySampleViewController.h

[backcolor=transparent]#import<UIKit/UIKit.h>

[backcolor=transparent]@interface MySampleViewController [backcolor=transparent]: UIViewController [backcolor=transparent]{

[backcolor=transparent]@private

UIProgressView[backcolor=transparent]* progressView_;

[backcolor=transparent]}

[backcolor=transparent]@end

[backcolor=transparent]接下来写一个叫做showProgressAlert的方法来创建并显示带有进度条的alert窗口,其中高亮的部分就是把进度条添加到alertView中:

[backcolor=transparent][backcolor=transparent]- [backcolor=transparent]([backcolor=transparent]void[backcolor=transparent])showProgressAlert[backcolor=transparent]:[backcolor=transparent]([backcolor=transparent]NSString[backcolor=transparent]*[backcolor=transparent])titlewithMessage[backcolor=transparent]:[backcolor=transparent]([backcolor=transparent]NSString[backcolor=transparent]*[backcolor=transparent])message [backcolor=transparent]{

UIAlertView[backcolor=transparent]* alertView [backcolor=transparent]= [backcolor=transparent][[backcolor=transparent][[backcolor=transparent][UIAlertViewalloc[backcolor=transparent]] initWithTitle[backcolor=transparent]:title

message[backcolor=transparent]:message

delegate[backcolor=transparent]:[backcolor=transparent]nil

cancelButtonTitle[backcolor=transparent]:[backcolor=transparent]nil

otherButtonTitles[backcolor=transparent]:[backcolor=transparent]nil[backcolor=transparent]]

autorelease[backcolor=transparent]];

progressView_ [backcolor=transparent]= [backcolor=transparent][[backcolor=transparent][UIProgressViewalloc[backcolor=transparent]] initWithProgressViewStyle[backcolor=transparent]:UIProgressViewStyleBar[backcolor=transparent]];

progressView_.frame [backcolor=transparent]= CGRectMake[backcolor=transparent]([backcolor=transparent]30, [backcolor=transparent]80, [backcolor=transparent]225, [backcolor=transparent]30[backcolor=transparent]);

[backcolor=transparent][alertView addSubview[backcolor=transparent]:progressView_[backcolor=transparent]];

[backcolor=transparent][alertView show[backcolor=transparent]];

[backcolor=transparent]}

[backcolor=transparent][backcolor=transparent]了让数据处理的子进程能够方便地修改进度条的值,再添加一个简单的方法:

[backcolor=transparent][backcolor=transparent][backcolor=transparent]- [backcolor=transparent]([backcolor=transparent]void[backcolor=transparent])updateProgress[backcolor=transparent]:[backcolor=transparent]([backcolor=transparent]NSNumber[backcolor=transparent]*[backcolor=transparent])progress [backcolor=transparent]{

progressView_.progress [backcolor=transparent]= [backcolor=transparent][progressfloatValue[backcolor=transparent]];

[backcolor=transparent]}

[backcolor=transparent][backcolor=transparent][backcolor=transparent]另外,数据处理完毕后,我们还需要让进度条以及alertView消失,由于之前并没有保存alertView的实例,可以通过进度条的superview访问之:

[backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent]- [backcolor=transparent]([backcolor=transparent]void[backcolor=transparent])dismissProgressAlert [backcolor=transparent]{

[backcolor=transparent]if [backcolor=transparent](progressView_ [backcolor=transparent]== [backcolor=transparent]nil[backcolor=transparent]) [backcolor=transparent]{

[backcolor=transparent]return;

[backcolor=transparent]}

[backcolor=transparent]if [backcolor=transparent]([backcolor=transparent][progressView_.superviewisKindOfClass[backcolor=transparent]:[backcolor=transparent][UIAlertViewclass[backcolor=transparent]][backcolor=transparent]][backcolor=transparent]) [backcolor=transparent]{

UIAlertView[backcolor=transparent]* alertView [backcolor=transparent]= [backcolor=transparent](UIAlertView[backcolor=transparent]*[backcolor=transparent])progressView_.superview;

[backcolor=transparent][alertViewdismissWithClickedButtonIndex[backcolor=transparent]:[backcolor=transparent]0 animated[backcolor=transparent]:[backcolor=transparent]NO[backcolor=transparent]];

[backcolor=transparent]}

[backcolor=transparent][progressView_release[backcolor=transparent]];

progressView_ [backcolor=transparent]= [backcolor=transparent]nil;

[backcolor=transparent]}

[backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent]假设处理数据的方法叫processData,当然它会在一个单独的线程中运行,下面的片段示意了如何更新进度条状态,以及最后如何让它消失。

[backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent]- [backcolor=transparent]([backcolor=transparent]void[backcolor=transparent])processData[backcolor=transparent]:[backcolor=transparent]([backcolor=transparent]int[backcolor=transparent])total [backcolor=transparent]{

[backcolor=transparent]for [backcolor=transparent]([backcolor=transparent]int i [backcolor=transparent]= [backcolor=transparent]0;i < total; [backcolor=transparent]++i[backcolor=transparent]) [backcolor=transparent]{

[backcolor=transparent]// Update UI to show progess.

[backcolor=transparent]float progress [backcolor=transparent]= [backcolor=transparent]([backcolor=transparent]float[backcolor=transparent])i [backcolor=transparent]/ total;

[backcolor=transparent]NSNumber[backcolor=transparent]* progressNumber [backcolor=transparent]= [backcolor=transparent][[backcolor=transparent]NSNumber numberWithFloat[backcolor=transparent]:progress[backcolor=transparent]];

[backcolor=transparent][selfperformSelectorOnMainThread[backcolor=transparent]:[backcolor=transparent]@selector[backcolor=transparent](updateProgress[backcolor=transparent]:[backcolor=transparent])

withObject[backcolor=transparent]:progressNumber

waitUntilDone[backcolor=transparent]:[backcolor=transparent]NO[backcolor=transparent]];

[backcolor=transparent]// Process.

[backcolor=transparent]// do it.

[backcolor=transparent]}

[backcolor=transparent]// Finished.

[backcolor=transparent][selfperformSelectorOnMainThread[backcolor=transparent]:[backcolor=transparent]@selector[backcolor=transparent](dismissProgressAlert[backcolor=transparent])

withObject[backcolor=transparent]:[backcolor=transparent]nil

waitUntilDone[backcolor=transparent]:[backcolor=transparent]YES[backcolor=transparent]];

[backcolor=transparent]// Other finalizations.

[backcolor=transparent]}

[backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent][backcolor=transparent]在实际使用中,带进度条的alert view大概长得是这样的:

图片:3292_111223105942_1.png

腾讯爱看 导航浏览 代码实现 

附件:  SliderMenu-1.zip (123 K) 下载次数:15

附件:  SliderMenu-2.zip (725 K) 下载次数:13

一个简易QQ列表,仅供学习

附件:  QQ_TableView.zip (613 K) 下载次数:18

iPhone开发——高级工程师必须具备的

网络,数据库操作,同步,异步操作,音频编解码

iphone自定义控件,通讯录,网络,电子书,控件特效 等源码

part 1--入门:1. xcode 版本下载 以及 iphone sdk 下载:

最新版本在此下载:

http://developer.apple.com/devcenter/ios/index.action

其他版本请看

http://connect.apple.com/cgi-bin... 1.0.1.1.0.3.3.3.3.1

2. 入门教程:

http://www.devdiv.com/thread-46499-1-1.html

part 2--代码、例程:

1. iphone编码转换方法:

http://www.devdiv.com/thread-70549-1-1.html

2. 自定义控件总结及常见页面效果:

http://www.devdiv.com/thread-63456-1-1.html

3. 通过custom url scheme启动应用程序:

http://www.devdiv.com/thread-30788-1-2.html

4. 歌曲剪切的代码例子

http://www.devdiv.com/thread-46712-1-1.html

5. ios电子书源码下载

http://www.devdiv.com/thread-65585-1-1.html

6. 条形码识别开源库:

http://www.devdiv.com/thread-41068-1-1.html

7. iPhone 利用CG API画一个饼图(Pie chart) :

http://www.devdiv.com/thread-38136-1-1.html

8. 从图片中的一点取色

http://www.devdiv.com/thread-67521-1-1.html

9. 两种自定义tabbar的方法

http://www.devdiv.com/thread-63143-1-1.html

10. cocos2d帧动画代码共享:

http://www.devdiv.com/thread-69243-1-1.html

11. UILocalNotification实现本地的闹钟提醒的方法

http://www.devdiv.com/thread-69786-1-1.html

12. 导航答的颜色设置

http://www.devdiv.com/thread-69792-1-1.html

13. IOS开发中常量的处理

http://www.devdiv.com/thread-69949-1-1.html

14. 使用定制的NSDictionary的方法,对NSArray进行排序

http://www.devdiv.com/thread-69948-1-1.html

15. UIImageView实现图片幻灯片

http://www.devdiv.com/thread-69941-1-1.html

16. 短信,电话,邮件,提示框

http://www.devdiv.com/thread-69940-1-1.html

17. 自己写的使用TouchXML解析器的一个小例子,分享一下。

http://www.devdiv.com/thread-69939-1-1.html

18. 网络等待indicator的界面设置

http://www.devdiv.com/thread-69938-1-1.html

19. 看到一种一套代码,可以多个目标(iPad/iPhone),多个版本(收费版本,试用版本)的方法。

http://www.devdiv.com/thread-69937-1-1.html

20. 去掉桌面的快捷方式的图标系统自带的高光效果

http://www.devdiv.com/thread-69936-1-1.html

21. 使用quartz2D绘制阴影的代码

http://www.devdiv.com/thread-70062-1-1.html

22. 分享一个iOS上实现的RSS的例子

http://www.devdiv.com/thread-70071-1-1.html

23. 分享一个别人的柱图

http://www.devdiv.com/thread-70067-1-1.html

24. 判断UITextField的输入只为数字的方法

http://www.devdiv.com/thread-70160-1-1.html

25. UITextField控件处理键盘弹出时遮住输入框的问题

http://www.devdiv.com/thread-70159-1-1.html

26. 分享一个好的文档 Object-C的语法与Cocoa框架-作者李海峰

http://www.devdiv.com/thread-70224-1-1.html

27. iOS 使用定制的NSDictionary的方法,对NSArray进行排序

http://www.devdiv.com/thread-70325-1-1.html

28. iOS录音相关的例子

http://www.devdiv.com/thread-70462-1-1.html

29. 通过代码添加联系人到通讯录的方法

http://www.devdiv.com/thread-70461-1-1.html

30. 中文转拼音

http://www.devdiv.com/thread-70535-1-1.html

31. 分享一个ASIHttpRequest 源码

http://www.devdiv.com/thread-70536-1-1.html

32. 短信添加联系人+多行textfield效果

http://www.devdiv.com/thread-68572-1-1.html

33. 让模拟器也支持GPS定位(模拟实现)

http://www.devdiv.com/thread-70613-1-1.html

34. 分享别人的两种闹钟的实现方法

http://www.devdiv.com/thread-70616-1-1.html

35. 播放 GIF 图片的代码

http://www.devdiv.com/thread-71496-1-1.html

36. 中文拼音排序的方法和代码例子

http://www.devdiv.com/thread-71499-1-1.html

37. iPhone 和 iPad 取色程序代码下载

http://www.devdiv.com/thread-71531-1-1.html

38. 官方文档《Xcode单元测试》中文版

http://www.devdiv.com/thread-71713-1-1.html

39. 使用MessageUI发送带附加的邮件

http://www.devdiv.com/thread-71718-1-1.html

40. NSCondition , 多线程同步例子

http://www.devdiv.com/thread-71719-1-1.html

41. 用cocos2d和chipmunk的DEMO

http://www.devdiv.com/thread-71720-1-1.html

42. Unity开发者杂志下载

http://www.devdiv.com/thread-71721-1-1.html

43.  iPhone按钮特效代码及效果图

http://www.devdiv.com/thread-71723-1-1.html

44. 玻璃破碎的特效,以及实现该特效的代码

http://www.devdiv.com/thread-71799-1-1.html

45. iPhone上画面切换特效及代码

http://www.devdiv.com/thread-71943-1-1.html

46. iPhone上的图书翻页特效代码

http://www.devdiv.com/thread-71940-1-1.html

part 3--经验分享:

1. ios4多任务机制:

http://www.devdiv.com/thread-47004-1-1.html

2. iPhone的Push(推送通知)功能原理浅析

http://www.devdiv.com/thread-67433-1-1.html

3. push机制详解:

http://www.devdiv.com/thread-41489-1-1.html

4. push消息的服务器端测试程序

http://www.devdiv.com/thread-69776-1-1.html

5.  push消息的服务端和客户端例子,测试通过的。

http://www.devdiv.com/thread-70070-1-1.html

6. iphone分区与目录结构:

http://www.devdiv.com/thread-31598-1-2.html

7. iPhone 路径大全:

http://www.devdiv.com/thread-31613-1-1.html

8. iPhone用户、用户组、权限解惑:

http://www.devdiv.com/thread-31617-1-1.html

9. ios系统架构:

http://www.devdiv.com/thread-30861-1-2.html

10. 上传一个老外的截屏工具

http://www.devdiv.com/thread-70152-1-1.html

part 4--教程:

1. Obj-C袖珍參考手冊(chm) :

http://www.devdiv.com/thread-30339-1-1.html

2. Xcode_cn开发员入门导引,挺不错的入门资料!

http://www.devdiv.com/thread-49926-1-1.html

3. iPhone开发基础教程(前12章)

http://www.devdiv.com/thread-65932-1-1.html

4. objective-c例程系列:

http://www.devdiv.com/forum.php?... ypeid&typeid=32

5. 电子书推荐:

http://www.devdiv.com/thread-64361-1-1.html

6. 分享一个UIWebView的使用的文档,希望对大家有用

http://www.devdiv.com/thread-69795-1-1.html

实现声音开关的代码

这段代码非常实用。

//Settings.h

CCMenuItem*soundOnItem;

CCMenuItem *soundOffItem;

CCMenuItemToggle *soundToggleItem;

//Settings.m

-(void)soundButtonTapped: (id) sender

{

if([CDAudioManager sharedManager].mute == TRUE){

[CDAudioManager sharedManager].mute = FALSE;

}

else {

[CDAudioManager sharedManager].mute = TRUE;

}

}

-(id)init{

if((self=[super init])){

self.isTouchEnabled = YES;

soundOnItem = [CCMenuItemImage itemFromNormalImage:@"soundon1.gif"selectedImage:@"soundon1.gif" target:nil selector:nil];

soundOffItem = [CCMenuItemImage itemFromNormalImage:@"soundoff1.png"selectedImage:@"soundoff1.png" target:nil selector:nil];

soundToggleItem = [CCMenuItemToggle itemWithTarget:selfselector:@selector(soundButtonTapped:) items:soundOnItem, soundOffItem, nil];

CCMenu *bottomMenu = [CCMenu menuWithItems:soundToggleItem, nil];

bottomMenu.position = ccp(25,95);

[self addChild: bottomMenu];

}

return self;

}

利用苹果自带相机进行录像的代码

这段利用苹果自带相机进行录像的代码对开发的应用中用到拍照、摄像功能的开发者应该有所帮助。

-(void) choosePhotoBySourceType:(UIImagePickerControllerCameraCaptureMode) sourceType

{

m_imagePickerController= [[[UIImagePickerController alloc] init] autorelease];

m_imagePickerController.modalTransitionStyle= UIModalTransitionStyleCoverVertical;

m_imagePickerController.sourceType= UIImagePickerControllerSourceTypeCamera;

m_imagePickerController.cameraDevice= UIImagePickerControllerCameraDeviceFront;

//m_imagePickerController.cameraCaptureMode= UIImagePickerControllerCameraCaptureModeVideo;

NSArray*sourceTypes = [UIImagePickerControlleravailableMediaTypesForSourceType:m_imagePickerController.sourceType];

if([sourceTypes containsObject:(NSString *)kUTTypeMovie ])

{

m_imagePickerController.mediaTypes=[NSArray arrayWithObjects:(NSString *)kUTTypeMovie,(NSString*)kUTTypeImage,nil];

}

//m_imagePickerController.cameraCaptureMode = sourceType;

//m_imagePickerController.mediaTypes

//imagePickerController.allowsEditing= YES;

[selfpresentModalViewController: m_imagePickerController animated:YES];

}

-(void) takePhoto

{

if([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{

[selfchoosePhotoBySourceType:nil];

}

}

// ImplementviewDidLoad to do additional setup after loading the view, typically from anib.

- (void)viewDidLoad{

[superviewDidLoad];

UIButton*takePhoto = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[takePhotosetTitle:@"录像" forState:UIControlStateNormal];

[takePhotoaddTarget:self action:@selector(takePhoto)forControlEvents:UIControlEventTouchUpInside];

takePhoto.frame= CGRectMake(50,100,100,30);

[self.viewaddSubview:takePhoto];

}

http://www.cocoachina.com/bbs/read.php?tid=73570&uid=39045&page=23

iphone开发笔记和技巧总结相关推荐

  1. ios学习--iphone开发笔记和技巧总结(原址持续更新)

    ios学习--iphone开发笔记和技巧总结(原址持续更新) 分类: ios Object-C2012-04-18 10:16 2716人阅读 评论(1) 收藏 举报 uiviewiphonelist ...

  2. iPhone开发中的技巧整理(四)

    iphone开发笔记 退回输入键盘 - (BOOL) textFieldShouldReturn:(id)textField{ [textField  resignFirstResponder]; } ...

  3. tlvaic3101音频芯片开发笔记调试技巧

    </pre><pre name="code" class="html"> tlvaic3101音频芯片开发笔记调试技巧4.解读芯片寄存器 ...

  4. iphone 开发笔记

    iphone 开发笔记 退回输入键盘   - (BOOL)textFieldShouldReturn:(id)textField{     [textField resignFirstResponde ...

  5. [每日100问][2011-10-11]iphone开发笔记,今天你肿了么

    [url=http://www.buildapp.net/iphone/show.asp?id=24500]为啥gamecenter在沙箱里好使,在正式环境中分数和成就都提交不了呢????[/url] ...

  6. [每日100问][2011-9-06]iphone开发笔记,今天你肿了么

    [url=http://www.buildapp.net/iphone/show.asp?id=5700]怎么让view保持不动,实现层次布局[/url] [url=http://www.builda ...

  7. [每日100问][2011-9-30]iphone开发笔记,今天你肿了么

    [url=http://www.buildapp.net/iphone/show.asp?id=18700]有apple打款的时候正巧要更换银行信息的么?[/url] [url=http://www. ...

  8. [每日100问][2011-9-08]iphone开发笔记,今天你肿了么

    [url=http://www.buildapp.net/iphone/show.asp?id=6700]请问,我想做iphone的真机调试,我的同一程序有办法对应多个固件版本吗?[/url] [ur ...

  9. [每日100问][2011-10-09]iphone开发笔记,今天你肿了么 编辑

    [url=http://www.buildapp.net/iphone/show.asp?id=23300]<font color=#0000FF>中秋不只赏月趣! 在香港和法國生活类获选 ...

最新文章

  1. 利用 PortableBasemapServer 发布地图服务
  2. layui table勾选框的修改_layui怎么设置checkbox勾选
  3. PostgreSQL用户角色和权限管理
  4. 在IDEA集成Github
  5. 废话少说 分析java抽象类与接口的区别
  6. 4. ubuntu php composer
  7. 局域网用户的限制与反限制
  8. 线性代数(一)矩阵和方程组
  9. 二、从零开始学逆向之XCTF-logmein
  10. Python之生成器练习
  11. numpy ndarry根据条件筛选数据
  12. 小武实习的debug日记
  13. HoloLens原理分析和硬件拆解
  14. 什么是gnuplot
  15. 20210327Java网络编程
  16. NMAP——如何使用
  17. ngrock内网穿透(Ngrok 和 Sunny-Ngrok )
  18. 超级电容与锂电池的比较
  19. Type接口的基础知识
  20. 基于pandas的粗糙集依赖度约简算法思路及实现

热门文章

  1. Python查询12306车票和使用selenium进行买票
  2. 网络、浏览器专题重点知识(含原理)
  3. MPLS TE原理描述
  4. 克鲁斯卡尔算法(Kruskal)求最小生成树(MST)过程详解
  5. 32位系统和64位系统的区别是什么
  6. 手机报彩信易操作平台
  7. 服务器启动文件夹,win10系统开机启动文件夹的路径是什么_网站服务器运行维护...
  8. 2014.10.9——Jim Foley教授讲座How real is real enough?
  9. 2opt邻域搜索算法—以旅行商问题为例
  10. python要英语基础吗_python学习需要英语基础吗?你真的想多了