iOS开发常用技巧

来源:互联网 发布:淘宝如何申请分销 编辑:程序博客网 时间:2024/05/16 16:09

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.隐藏状态栏

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

4.自动适应父视图大小

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

5.UITableView的一些方法

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

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

NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];NSArray *array = [NSArray arrayWithContentsOfFile:path];

7.获取触摸的点

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

8.获取触摸的属性

@property(nonatomic,readonly) NSTimeInterval      timestamp;@property(nonatomic,readonly) UITouchPhase        phase;@property(nonatomic,readonly) NSUInteger          tapCount;

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

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];

10.NSUserDefaults注意事项

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

11.获取Documents目录

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

12.获取tmp目录

NSString *tmpPath = NSTemporaryDirectory();

13.利用Safari打开一个链接

NSURL *url = [NSURL URLWithString:@"http://baidu.com"];[[UIApplication sharedApplication] openURL:url];

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

<UIWebViewDelegate>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];[webView loadRequest:request];

15.UIWebView和html的简单交互

myWebView = [[UIWebView alloc]initWithFrame:self.view.bounds];[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];NSError *error;NSString *errorString = [NSString stringWithFormat:@"<html><center><font size=+5 color='red'>AnError Occurred;<br>%@</font></center></html>",error];[myWebView loadHTMLString:errorString baseURL:nil];//页面跳转了以后,停止载入- (void)viewWillDisappear:(BOOL)animated {    if (myWebView.isLoading) {        [myWebView stopLoading];    }    myWebView.delegate = nil;    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;}

16.汉字转码

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

17.处理键盘通知

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

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

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

19.设置日期格式

dateFormatter = [[NSDateFormatter alloc]init];dateFormatter.locale = [NSLocale currentLocale];dateFormatter.calendar = [NSCalendar autoupdatingCurrentCalendar];dateFormatter.timeZone = [NSTimeZone defaultTimeZone];dateFormatter.dateStyle = NSDateFormatterShortStyle;NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

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

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];

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

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

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

NSString *originalString = @"(123)123123abc";NSMutableString *strippedString = [NSMutableString stringWithCapacity:originalString.length];NSScanner *scanner = [NSScanner scannerWithString:originalString];NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"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 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];    if ([predicate evaluateWithObject:myString]) {        //implement    }

24.设置UITableView的滚动条颜色

self.tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;

25.使用NSURLConnection下载数据

1. 创建对象NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];    [NSURLConnection connectionWithRequest:request delegate:self];2. NSURLConnection delegate 委托方法- (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 {    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;    NSString *returnString = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];    firstTimeDownloaded = YES;}

26.隐藏状态栏

[UIApplication sharedApplication].statusBarHidden = YES;

28.读取一般性文件

- (void)readFromTXT {    NSString *tmp;    NSArray *lines;//将文件转化为一行一行的    lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] componentsSeparatedByString:@"\n"];    NSEnumerator *nse = [lines objectEnumerator];    //读取<>里的内容    while (tmp == [nse nextObject]) {        NSString *stringBetweenBrackets = nil;        NSScanner *scanner = [NSScanner scannerWithString: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.调用电话,短信,邮件

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

31.获取版本信息

UIDevice *myDevice = [UIDevice currentDevice];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;}

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

SearchBar *mySearchBar = [[UISearchBar alloc]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;

34.使用MD5对NSData或者NSString加密

//需要引入此头文件来使用CC_MD5#import <CommonCrypto/CommonDigest.h>//针对NSString的加密①- (NSString *) md5:(NSString *) input{   const char *cStr = [input UTF8String];   unsigned char digest[CC_MD5_DIGEST_LENGTH];   CC_MD5( cStr, strlen(cStr), digest );  NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];   for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) [output appendFormat:@"%02x", digest[i]];  return output;}//针对NSString的加密②- (NSString *)md5:(NSString *) input{   const char *cStr = [input UTF8String];   unsigned char result[CC_MD5_DIGEST_LENGTH];   CC_MD5( cStr, (int)strlen(cStr), result );   return [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",            result[0], result[1], result[2], result[3],            result[4], result[5], result[6], result[7],            result[8], result[9], result[10], result[11],            result[12], result[13], result[14], result[15]            ];}//针对NSData的加密- (NSString*)md5:(NSData *)data{    unsigned char result[CC_MD5_DIGEST_LENGTH];    CC_MD5( data.bytes, (int)data.length, result );     return [NSString stringWithFormat:            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",            result[0], result[1], result[2], result[3],            result[4], result[5], result[6], result[7],            result[8], result[9], result[10], result[11],            result[12], result[13], result[14], result[15]            ];  }

35.获取显示在屏幕上的所有cell

self.tableView.visibleCells

36.判断NSString中是否包含中文

-(BOOL)isChinese:(NSString *)str{    NSString *match=@"(^[\u4e00-\u9fa5]+$)";    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];    return [predicate evaluateWithObject:str];}

37.去掉TableView未占满屏幕的空白行

self.tableView.tableFooterView = [UIView new];

38.iOS之UITextField 禁止粘贴

//方法1:重写下面方法- (BOOL)canPerformAction:(SEL)action withSender:(id)sender    {        if (action == @selector(paste:))//禁止粘贴            return NO;        if (action == @selector(select:))// 禁止选择               return NO;           if (action == @selector(selectAll:))// 禁止全选               return NO;          return [super canPerformAction:action withSender:sender];    }//方法2:-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {    UIMenuController *menuController = [UIMenuController sharedMenuController];    if (menuController) {        [UIMenuController sharedMenuController].menuVisible = NO;    }    return NO;}

39.iOS9下将NSString转为UTF8

url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

40.Search Bar 怎样去掉背景的颜色(storyboard里只能设置background颜色,可是发现clear Color无法使用)

[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
1 0