iOS开发零碎知识点整理
2016-08-13 08:54
411 查看
转载自标哥的技术博客:http://www.huangyibiao.com/ios-good-knowledge/
另外添加了自己之前留意的开发小点加在后面,以后翻阅备用1.调用代码使APP进入后台
1 2 3 4 | [[UIApplicationsharedApplication] performSelector:@selector(suspend)]; |
2.带中文的URL处理
大概举个例子,类似下面的URL,里面直接含有中文,可能导致播放不了,那么我们要处理一个这个URL,因为他太操蛋了,居然用中文。1 2 3 4 | // http://static.tripbe.com/videofiles/视频/我的自拍视频.mp4 NSString*path =(__bridge_transferNSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridgeCFStringRef)model.mp4_url, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); |
3.取WebView高度
个人最常用的获取方法,感觉这个比较靠谱:1 2 3 4 5 6 7 | - (void)webViewDidFinishLoad:(UIWebView*)webView { CGFloatheight=[[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]; CGRectframe=webView.frame; webView.frame=CGRectMake(frame.origin.x,frame.origin.y,frame.size.width,height); } |
4.View设置图片
第一种方法
利用的UIView的设置背景颜色方法,用图片做图案颜色,然后传给背景颜色。1 2 3 4 5 | UIColor *bgColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"bgImg.png"]; UIView*myView=[[UIViewalloc] initWithFrame:CGRectMake(0,0,320,480)]; [myView setBackGroundColor:bgColor]; |
第二种方法
1 2 3 4 5 6 | UIImage *image=[UIImage imageNamed:@"yourPicName@2x.png"]; yourView.layer.contents=(__bridgeid)image.CGImage; // 设置显示的图片范围 yourView.layer.contentsCenter=CGRectMake(0.25,0.25,0.5,0.5);//四个值在0-1之间,对应的为x,y,width,height。 |
5.去TableView分割线
1 2 3 | yourTableView.tableFooterView=[UIViewnew]; |
6.调cell分割线位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | - (void)viewDidLayoutSubviews{ if([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]){ [self.mytableview setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)]; } if([self.mytableview respondsToSelector:@selector(setLayoutMargins:)]) { [self.mytableview setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; } } #pragma mark - cell分割线 -(void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath { if([cell respondsToSelector:@selector(setSeparatorInset:)]){ [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)]; } if([cell respondsToSelector:@selector(setLayoutMargins:)]){ [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)]; } } |
7、Label注意事项
UILabel和UIImageView的交互userInteractionEabled默认为NO。那么如果你把这两个类做为父试图的话,里面的所有东东都不可以点击哦。曾经有一个人,让我帮忙调试bug,他调试很久没搞定,就是把WMPlayer对象(播放器对象)放到一个UIImageView上面。这样imageView addSubView:wmPlayer 后,播放器的任何东东都不能点击了。userInteractionEabled设置为YES即可。
8、搜索条Cancel改标题
1 2 3 4 5 6 7 8 9 10 11 | - (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar { searchController.searchBar.showsCancelButton=YES; UIButton*canceLBtn=[searchController.searchBar valueForKey:@"cancelButton"]; [canceLBtn setTitle:@"取消" forState:UIControlStateNormal]; [canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal]; searchBar.showsCancelButton=YES; returnYES; } |
9、TableView收键盘
一个属性搞定,效果好(UIScrollView同样可以使用) 以前是不是觉得[self.view endEditing:YES];很屌,这个下面的更屌。1 2 3 | yourTableView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag; |
10、NSTimer
NSTimer计算的时间并不精确NSTimer需要添加到runLoop运行才会执行,但是这个runLoop的线程必须是已经开启。
NSTimer会对它的tagert进行retain,我们必须对其重复性的使用intvailte停止。target如果是self(指UIViewController),那么VC的retainCount+1,如果你不释放NSTimer,那么你的VC就不会dealloc了,内存泄漏了。
11、十六进制取颜色
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 | + (UIColor*)colorWithHexString:(NSString*)color { NSString*cString=[[color stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if([cStringlength]<6){ return[UIColorclearColor]; } // strip 0X if it appears if([cString hasPrefix:@"0X"]) cString=[cString substringFromIndex:2]; if([cString hasPrefix:@"#"]) cString=[cString substringFromIndex:1]; if([cStringlength]!=6) return[UIColorclearColor]; // Separate into r, g, b substrings NSRangerange; range.location=0; range.length=2; //r NSString*rString=[cString substringWithRange:range]; //g range.location=2; NSString*gString=[cString substringWithRange:range]; //b range.location=4; NSString*bString=[cString substringWithRange:range]; // Scan values unsignedintr,g,b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return[UIColor colorWithRed:((float)r/255.0f) green:((float)g/255.0f) blue:((float)b/255.0f) alpha:1.0f]; } |
12、获取今天是星期几
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 | + (NSString*) getweekDayStringWithDate:(NSDate*)date { NSCalendar*calendar=[[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];// 指定日历的算法 NSDateComponents*comps=[calendar components:NSWeekdayCalendarUnit fromDate:date]; // 1 是周日,2是周一 3.以此类推 NSNumber*weekNumber=@([compsweekday]); NSIntegerweekInt=[weekNumberintegerValue]; NSString*weekDayString= @"(周一)"; switch(weekInt){ case 1: { weekDayString=@"(周日)"; } break; case 2: { weekDayString=@"(周一)"; } break; case 3: { weekDayString=@"(周二)"; } break; case 4: { weekDayString=@"(周三)"; } break; case 5: { weekDayString=@"(周四)"; } break; case 6: { weekDayString=@"(周五)"; } break; case 7: { weekDayString=@"(周六)"; } break; default: break; } returnweekDayString; } |
13、UIView的部分圆角问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | UIView *view2=[[UIViewalloc] initWithFrame:CGRectMake(120,10,80,80)]; view2.backgroundColor=[UIColorredColor]; [self.view addSubview:view2]; UIBezierPath *maskPath=[UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10,10)]; CAShapeLayer*maskLayer=[[CAShapeLayeralloc] init]; maskLayer.frame=view2.bounds; maskLayer.path=maskPath.CGPath; view2.layer.mask=maskLayer; //其中,byRoundingCorners:UIRectCornerBottomLeft |UIRectCornerBottomRight //指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有: *UIRectCornerTopLeft * UIRectCornerTopRight *UIRectCornerBottomLeft * UIRectCornerBottomRight *UIRectCornerAllCorners |
14、滑动时隐藏navigationBar
1 2 3 | navigationController.hidesBarsOnSwipe=Yes; |
15、iOS画虚线
记得先 QuartzCore框架的导入1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #import <QuartzCore/QuartzCore.h> CGContextRef context=UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSetLineWidth(context,2.0); CGContextSetStrokeColorWithColor(context,[UIColorwhiteColor].CGColor); CGFloat lengths[]={10,10}; CGContextSetLineDash(context,0,lengths,2); CGContextMoveToPoint(context,10.0,20.0); CGContextAddLineToPoint(context,310.0,20.0); CGContextStrokePath(context); CGContextClosePath(context); |
16、自动布局多行UILabel问题
需要设置其preferredMaxLayoutWidth属性才能正常显示多行内容。另外如果出现显示不全文本,可以在计算的结果基础上+0.5。1 2 3 | CGFloat h=[model.message boundingRectWithSize:CGSizeMake([UIScreenmainScreen].bounds.size.width-kGAP-kAvatar_Size-2*kGAP,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5; |
17、禁止运行时自动锁屏
1 2 3 | [[UIApplicationsharedApplication] setIdleTimerDisabled:YES]; |
18、KVC相关
KVC同时还提供了很复杂的函数,主要有下面这些①简单集合运算符
简单集合运算符共有@avg, @count , @max , @min ,@sum5种,都表示啥不用我说了吧, 目前还不支持自定义。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 | @interface Book : NSObject @property(nonatomic,copy) NSString*name; @property (nonatomic,assign) CGFloatprice; @end @implementationBook @end Book*book1=[Booknew]; book1.name=@"The Great Gastby"; book1.price=22; Book *book2=[Booknew]; book2.name=@"Time History"; book2.price=12; Book*book3=[Booknew]; book3.name=@"Wrong Hole"; book3.price=111; Book*book4=[Booknew]; book4.name=@"Wrong Hole"; book4.price=111; NSArray*arrBooks=@[book1,book2,book3,book4]; NSNumber*sum=[arrBooks valueForKeyPath:@"@sum.price"]; NSLog(@"sum:%f",sum.floatValue); NSNumber*avg=[arrBooks valueForKeyPath:@"@avg.price"]; NSLog(@"avg:%f",avg.floatValue); NSNumber*count=[arrBooks valueForKeyPath:@"@count"]; NSLog(@"count:%f",count.floatValue); NSNumber*min=[arrBooks valueForKeyPath:@"@min.price"]; NSLog(@"min:%f",min.floatValue); NSNumber*max=[arrBooks valueForKeyPath:@"@max.price"]; NSLog(@"max:%f",max.floatValue); |
打印结果
1 2 3 4 5 6 7 | 2016-04-2016:45:54.696KVCDemo[1484:127089] sum:256.000000 2016-04-2016:45:54.697KVCDemo[1484:127089] avg:64.000000 2016-04-2016:45:54.697KVCDemo[1484:127089] count:4.000000 2016-04-2016:45:54.697KVCDemo[1484:127089] min:12.000000 NSArray 快速求总和最大值最小值 和平均值 |
例2
1 2 3 4 5 6 7 8 | NSArray *array=[NSArray arrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil]; CGFloatsum=[[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg=[[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloatmax=[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min=[[array valueForKeyPath:@"@min.floatValue"] floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min); |
19、用MBProgressHud问题
尽量不要加到UIWindow上,加self.view上即可。如果加UIWindow上在iPad上,旋转屏幕的时候MBProgressHud不会旋转。之前有人遇到这个bug,我让他改放到self.view上即可解决此bug。20、强制App直接退出
1 2 3 4 5 6 7 8 9 10 11 | - (void)exitApplication{ AppDelegate*app=[UIApplicationsharedApplication].delegate; UIWindow*window=app.window; [UIView animateWithDuration:1.0f animations:^{ window.alpha=0; } completion:^(BOOLfinished){ exit(0); }]; } |
21、Label行间距
1 2 3 4 5 6 7 8 9 10 11 12 | NSMutableAttributedString*attributedString= [[NSMutableAttributedStringalloc] initWithString:self.contentLabel.text]; NSMutableParagraphStyle*paragraphStyle= [[NSMutableParagraphStylealloc] init]; [paragraphStyle setLineSpacing:3]; //调整行间距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[self.contentLabel.textlength])]; self.contentLabel.attributedText=attributedString; |
22、pod更新慢的问题
1 2 3 4 | pod install–verbose–no-repo-update podupdate–verbose–no-repo-update |
23、MRC和ARC混编设置方式
在XCode中targets的build phases选项下Compile Sources下选择->不需要arc编译的文件,双击输入 -fno-objc-arc 即可MRC工程中也可以使用ARC的类,方法如下:
在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件,双击输入 -fobjc-arc 即可
24、cell对勾颜色修改
1 2 3 | _yourTableView.tintColor=[UIColorredColor]; |
25、同时按两个按钮问题
1 2 3 | [button setExclusiveTouch:YES]; |
26、修改占位符颜色和大小
1 2 3 4 5 | textField.placeholder=@"请输入用户名"; [textField setValue:[UIColorredColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"]; |
27、禁止复制粘贴
1 2 3 4 5 6 7 8 9 | - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if([UIMenuControllersharedMenuController]){ [UIMenuControllersharedMenuController].menuVisible=NO; } returnNO; } |
28、进入App在AppStore页面
先用iTunes Link Maker找到软件在访问地址,格式为itms-apps://ax.itunes.apple.com/…,然后复制链接!1 2 3 4 5 6 7 | #define ITUNESLINK @"itms-apps://ax.itunes.apple.com/..." NSURL*url=[NSURL URLWithString:ITUNESLINK]; if([[UIApplicationsharedApplication] canOpenURL:url]){ [[UIApplicationsharedApplication] openURL:url]; } |
29、隐藏系统tabbar
二级、三级界面隐藏系统tabbar方法.1、单个处理
1 2 3 4 5 | YourViewController *yourVC=[YourViewControllernew]; yourVC.hidesBottomBarWhenPushed=YES; [self.navigationController pushViewController:yourVC animated:YES]; |
2.统一在基类里面处理
新建一个类BaseNavigationController继承UINavigationController,然后重写 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated这个方法。所有的push事件都走此方法。1 2 3 4 5 6 7 8 9 10 11 12 | @interface BaseNavigationController: UINavigationController @end -(void)pushViewController:(UIViewController*)viewController animated:(BOOL)animated{ [super pushViewController:viewController animated:animated]; if(self.viewControllers.count>1){ viewController.hidesBottomBarWhenPushed=YES; } } |
30、取消系统的返回手势
一行代码搞定:1 2 3 | self.navigationController.interactivePopGestureRecognizer.enabled=NO; |
31、改WebView字体/颜色
UIWebView设置字体大小,颜色,字体: UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置 在webView加载完毕后:1 2 3 4 5 6 | - (void)webViewDidFinishLoad:(UIWebView*)webView{ NSString*str=@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'"; [webView stringByEvaluatingJavaScriptFromString:str]; } |
NSString *jsString= [[NSStringalloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor]; [webView stringByEvaluatingJavaScriptFromString:jsString];
32、判断当前控制器是由哪个控制器推进来的
NSArray * vcsArray = self.navigationController.viewControllers; NSInteger vcCount = vcsArray.count; UIViewController *lastVC = vcsArray[vcCount-2];//最后一个vc是自己,倒数第二个是上一个控制器。 // 假设cVC来源可能是 VCClass1,VCClass2的实力push来的 // 那么只要判断出lastVC类型,就可以判断其是谁push来的: if ([lastVC isKindOfClass:[NHUserViewController class]]) { }else if ([lastVC isKindOfClass:[NHOrderConfirmViewController class]]){ }
33、导航栏设置为不透明
self.navigationController.navigationBar.translucent = NO;iOS 导航栏透明,变色动画
http://www.jianshu.com/p/bcac3a61702f相关文章推荐
- iOS开发中 一些零碎的知识点,
- [置顶] iOS开发零碎知识点
- iOS开发零碎知识点
- iOS 在开发过程中的 零碎知识点
- IOS 游戏/应用开发相关知识点整理
- iOS开发零碎知识点
- iOS开发中的零碎知识点笔记 韩俊强的博客
- iOS开发零碎知识点
- iOS开发零碎知识点
- 【IOS】1.xcode 开发的零碎整理 | ARC 关闭键盘
- iOS开发中的零碎知识点笔记 韩俊强的博客
- iOS开发零碎知识点
- iOS开发零碎知识点
- IOS 游戏/应用开发相关知识点整理
- iOS开发零碎知识点
- iOS开发零碎知识点---(有一些还是比较实用的)。
- iOS开发零碎知识点(一)
- iOS开发零碎知识点
- ios 开发中零碎易错知识点
- ios开发一些零碎的知识点(一)