记录各种iOS开发技巧

1.返回输入键盘

`- (BOOL)textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];

return YES;

}`

2.CGRect

CGRectFromString(<#NSString *string#>)//有字符串恢复出矩形CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)//创建较小或者较大的矩形CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)//判断两巨星是否交叉,是否重叠CGRectZero//高度和宽度为零的,位于(0,0)的矩形常量

3.隐藏状态栏

###[UIApplicationsharedApplication]setStatusBarHidden:<#(BOOL)#> withAnimation:<#(UIStatusBarAnimation)#>//隐藏状态栏

4.自动适应父视图大小 

self.view.autoresizesSubviews=YES;self.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

5.UITableView的一些方法

这里我自己做了个测试,缩进级别设置为行号,row越大,缩进越多-(NSInteger)tableView:(UITableView*)tableView indentationLevelForRowAtIndexPath:(NSIndexPath*)indexPath{NSIntegerrow=indexPath.row;returnrow;}

6.把plist文件中的数据赋给数组

NSString*path=[[NSBundlemainBundle]pathForResource:@"States"ofType:@"plist"];NSArray*array=[NSArrayarrayWithContentsOfFile:path];

7.获取触摸的点

-(CGPoint)locationInView:(UIView*)view;-(CGPoint)previousLocationInView:(UIView*)view;

8.获取触摸的属性

@property(nonatomic,readonly)NSTimeIntervaltimestamp;@property(nonatomic,readonly)UITouchPhasephase;@property(nonatomic,readonly)NSUIntegertapCount;

9.从plist中获取数据赋给字典

NSString*plistPath=[[NSBundlemainBundle]pathForResource:@"book"ofType:@"plist"];NSDictionary*dictionary=[NSDictionarydictionaryWithContentsOfFile:plistPath];

10.NSUserDefaults注意事项

设置完了以后如果存储的东西比较重要的话,一定要同步一下[[NSUserDefaultsstandardUserDefaults]synchronize];

11.获取Documents目录

NSString*documentsDirectory=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];

12.获取tmp目录

NSString*tmpPath=NSTemporaryDirectory();

13.利用Safari打开一个链接

NSURL*url=[NSURLURLWithString:@"http://baidu.com"];[[UIApplicationsharedApplication]openURL:url];

14.利用UIWebView显示pdf文件,网页等等

UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];

webView.delegate = self;

webView.scalesPageToFit = YES;

webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

[webView setAllowsInlineMediaPlayback:YES];

[self.view addSubview:webView];

NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"pdf"];

NSURL *url = [NSURL fileURLWithPath:pdfPath];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:5];

15.UIWebView和html的简单交互

myWebView=[[UIWebViewalloc]initWithFrame:self.view.bounds];[myWebView loadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.baidu.com"]]];NSError*error;NSString*errorString=[NSStringstringWithFormat:@"AnError Occurred;
%@",error];[myWebView loadHTMLString:errorString baseURL:nil];//页面跳转了以后,停止载入-(void)viewWillDisappear:(BOOL)animated{if(myWebView.isLoading){[myWebView stopLoading];}myWebView.delegate=nil;[UIApplicationsharedApplication].networkActivityIndicatorVisible=NO;}

16.汉字转码

NSString*oriString=@"\u67aa\u738b";NSString*escapedString=[oriString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

17.处理键盘通知

先注册通知,然后实现具体当键盘弹出来要做什么,键盘收起来要做什么-(void)registerForKeyboardNotifications{keyboardShown=NO;//标记当前键盘是没有显示的[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWasShown:)name:UIKeyboardWillShowNotificationobject:nil];[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWasHidden:)name:UIKeyboardDidHideNotificationobject:nil];}//键盘显示要做什么-(void)keyboardWasShown:(NSNotification*)notification{if(keyboardShown){return;}NSDictionary*info=[notification userInfo];NSValue*aValue=[info objectForKey:UIKeyboardFrameBeginUserInfoKey];CGSizekeyboardSize=[aValueCGRectValue].size;CGRectviewFrame=scrollView.frame;viewFrame.size.height=keyboardSize.height;CGRecttextFieldRect=activeField.frame;[scrollView scrollRectToVisible:textFieldRect animated:YES];keyboardShown=YES;}-(void)keyboardWasHidden:(NSNotification*)notification{NSDictionary*info=[notification userInfo];NSValue*aValue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];CGSizekeyboardSize=[aValueCGRectValue].size;CGRectviewFrame=scrollView.frame;viewFrame.size.height+=keyboardSize.height;scrollView.frame=viewFrame;keyboardShown=NO;}

18.点击键盘的next按钮,在不同的textField之间换行

-(BOOL)textFieldShouldReturn:(UITextField*)textField{if([textField returnKeyType]!=UIReturnKeyDone){NSIntegernextTag=[textField tag]+1;UIView*nextTextField=[self.tableView viewWithTag:nextTag];[nextTextField becomeFirstResponder];}else{[textField resignFirstResponder];}returnYES;}

19.设置日期格式

dateFormatter=[[NSDateFormatteralloc]init];dateFormatter.locale=[NSLocalecurrentLocale];dateFormatter.calendar=[NSCalendarautoupdatingCurrentCalendar];dateFormatter.timeZone=[NSTimeZonedefaultTimeZone];dateFormatter.dateStyle=NSDateFormatterShortStyle;NSLog(@"%@",[dateFormatter stringFromDate:[NSDatedate]]);

20.加载大量图片的时候,可以使用

NSString*imagePath=[[NSBundlemainBundle]pathForResource:@"icon"ofType:@"png"];UIImage*myImage=[UIImageimageWithContentsOfFile:imagePath];

21.有时候在iPhone游戏中,既要播放背景音乐,同时又要播放比如枪的开火音效。

NSString*musicFilePath=[[NSBundlemainBundle]pathForResource:@"xx"ofType:@"wav"];NSURL*musicURL=[NSURL fileURLWithPath:musicFilePath];AVAudioPlayer*musicPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:musicURL error:nil];[musicPlayer prepareToPlay];musicPlayer.volume=1;musicPlayer.numberOfLoops=-1;//-1表示一直循环

22.从通讯录中读取电话号码,去掉数字之间的-

NSString*originalString=@"(123)123123abc";NSMutableString*strippedString=[NSMutableStringstringWithCapacity:originalString.length];NSScanner*scanner=[NSScannerscannerWithString:originalString];NSCharacterSet*numbers=[NSCharacterSetcharacterSetWithCharactersInString:@"0123456789"];while([scanner isAtEnd]==NO){NSString*buffer;if([scanner scanCharactersFromSet:numbers intoString:&buffer]){[strippedString appendString:buffer];}else{scanner.scanLocation=[scanner scanLocation]+1;}}NSLog(@"%@",strippedString);

23.正则判断:字符串只包含字母和数字

NSString*myString=@"Letter1234";NSString*regex=@"[a-z][A-Z][0-9]";NSPredicate*predicate=[NSPredicatepredicateWithFormat:@"SELF MATCHES %@",regex];if([predicate evaluateWithObject:myString]){//implement}

24.设置UITableView的滚动条颜色

self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;

网络编程 开发web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过apple的审查的。 系统自带的网络检查是原生的,AFNetworking也为我们添加了相关检测机制,所以这个直接在介绍AFNetworking的时候详解吧。

25.使用NSURLConnection下载数据

1.创建对象NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.baidu.com"]];[NSURLConnectionconnectionWithRequest:requestdelegate:self];2.NSURLConnectiondelegate委托方法-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{}-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{}-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{}-(void)connectionDidFinishLoading:(NSURLConnection*)connection{}3.实现委托方法-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{self.receiveData.length=0;//先清空数据}-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{[self.receiveData appendData:data];}-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{//错误处理}-(void)connectionDidFinishLoading:(NSURLConnection*)connection{[UIApplicationsharedApplication].networkActivityIndicatorVisible=NO;NSString*returnString=[[NSStringalloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];firstTimeDownloaded=YES;}

iOS的动画以及自定义图形,开个专栏总结。

26.隐藏状态栏

[UIApplicationsharedApplication].statusBarHidden=YES;

27..m文件与.mm文件的区别

.m文件是objective-c文件.mm文件相当于c++或者c文件

Safari其实没有把内存的缓存写到存储卡上

28.读取一般性文件

-(void)readFromTXT{NSString*tmp;NSArray*lines;//将文件转化为一行一行的lines=[[NSStringstringWithContentsOfFile:@"testFileReadLines.txt"]componentsSeparatedByString:@"\n"];NSEnumerator*nse=[lines objectEnumerator];//读取<>里的内容while(tmp==[nse nextObject]){NSString*stringBetweenBrackets=nil;NSScanner*scanner=[NSScannerscannerWithString:tmp];[scanner scanUpToString:@"<"intoString:nil];[scanner scanString:@"<"intoString:nil];[scanner scanUpToString:@">"intoString:&stringBetweenBrackets];NSLog(@"%@",[stringBetweenBrackets description]);}}

29.隐藏UINavigationBar

[self.navigationController setNavigationBarHidden:YES animated:YES];

30.调用电话,短信,邮件

[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"mailto:apple@mac.com?Subject=hello"]];sms://调用短信tel://调用电话itms://打开MobileStore.app

31.获取版本信息

UIDevice*myDevice=[UIDevicecurrentDevice];NSString*systemVersion=myDevice.systemVersion;

32.UIWebView的使用

webView.delegate = self;

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

NSURL *url = request.URL;

NSString *urlStirng = url.absoluteString;

NSLog(@"%@",urlStirng);

return YES;

}

UIButton的title和image不能同时显示UINavigationItem也是

33.NSNotificationCenter带参数发送

MPMoviePlayerController*theMovie=[[MPMoviePlayerControlleralloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(myMovieFinishedCallback:)name:MPMoviePlayerPlaybackDidFinishNotificationobject:theMovie];[theMovie play];-(void)myMovieFinishedCallback:(NSNotification*)aNotification{MPMoviePlayerController*theMovie=[aNotificationobject];[[NSNotificationCenterdefaultCenter]removeObserver:selfname:MPMoviePlayerPlaybackDidFinishNotificationobject:theMovie];}

34.延迟一段时间执行某个函数

[selfperformSelector:@selector(dismissModal)withObject:selfafterDelay:1.0];

35.用NSDateFormatter调整时间格式代码

NSDateFormatter*dateFormatter=[[NSDateFormatteralloc]init];dateFormatter.dateFormat=@"yyyy-MM-dd HH:mm:ss";NSString*currentDateStr=[dateFormatter stringFromDate:[NSDatedate]];

36.UIView设置成圆角的方法

mainView.layer.cornerRadius=6;mainView.layer.masksToBounds=YES;

Objective-C 内存管理

一个对象可以有一个或多个拥有者

当它一个拥有者都没有的时候,它就会被回收

如果想保留一个对象不被回收,你就必须成为它的拥有者

关键字

alloc 为对象分配内存,计数设为1,并返回此对象。

copy 复制一个对象,此对象计数为1,返回此对象。你将成为此克隆对象的拥有者。

retain 对象计数+1,并成为次对象的拥有者。

release 对象计数-1,并丢掉此对象。

autorelease 在未来的某一个时刻,对象计数-1。并在未来的某个时间放弃此对象。

原则

一个代码块内要确保copy,alloc 和 retain 的使用数量与 release 和 autorelease 的数量相等。

在使用以 alloc 或 new 开头或包含 copy 的方法,或 retain 一个对象时,你将会编程它的拥有者。

实现 dealloc 方法,这是系统当 retain -> 0 的时候,自动调用的。手动调用会引起 retain count 计数错误(多一次的 release)。

iPhone 更改键盘右下角按键的 type

SearchBar*mySearchBar=[[UISearchBaralloc]init];mySearchBar.frame=CGRectMake(0,0,self.view.bounds.size.width,44);mySearchBar.placeholder=@"placeholderString";mySearchBar.delegate=self;[self.view addSubview:mySearchBar];UITextField*searchField=[[mySearchBar subviews]lastObject];searchField.returnKeyType=UIReturnKeyDone;

总结

不积跬步无以至千里,不积小流无以成江海。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,619评论 2 7
  • iphone开发笔记 退回输入键盘 - (BOOL) textFieldShouldReturn:(id)text...
    爱易寒曲易散阅读 613评论 0 1
  • 我高二的时候,周启航念初二。 我们在大不列颠度过了不可描述的一个月,现在想起来,我还记得大家一起含泪吃着难吃到天上...
    不沉大师傅阅读 217评论 0 1
  • 我们有多久没有去看过星星? 仿佛很久以来 我们已渐习惯: 倚着昂贵的原木桌椅 就着隐约的灯光 品茶,或酒 谈论对自...
    浣秋阅读 333评论 2 0
  • 第一次在简书上写东西,好紧张;文笔那么差劲,会不会被骂,会不会被鄙视,好紧张啊……唉,豁出去了,管他咯,谁在乎呢,...
    岭南七哥阅读 171评论 0 0