记录一些常用和不常用的iOS知识点,防止遗忘丢失。来源为收集自己项目中用到的或者整理看到博客中的知识点,如有错误,欢迎大家批评指正;如有好的知识点,也欢迎大家联系我,添加上去!谢谢!
本篇文章由标哥的技术博客编辑整理发布到本站,为了更美观,内容作了一些调整,但整体没有太大的变动。当然内容也会在后续加一些补充,如果大家有更多的好知识点,可在评论中指出,站长会收集并整理到本篇文章中。
本篇中讲到的知识点都是非常常用的知识的,像处理URL中带有中文的链接、挂起App、在与UIWebView交互时,经常需要取UIWebView的内容的高度然后设置视图总高度、给视图设置图片、修改UITabelView的分割线、键盘收起、调整分割线位置、NSTimer使用、获取星期几、隐藏导航、隐藏tabbar、KVC相关、禁止锁屏、App强制退出、修改占位符颜色及大小、取消系统返回手势、修改webview字段大小和颜色等。
在开发中,总会遇到很多小问题,收集起来既对自己有帮助,再分享给大家,对大家都有帮助!
相信你在开发中也会遇到过很多的小细节问题,大家一直来收集吧!想要快速的成长,除了不断地训练自己之外,还需要不断地总结,将自己的毛病慢慢改掉。
对于我个人而言,成长的过程中写了很多的项目来训练自己,扩张个人的技术视野,同时还不断地写文章,做总结,将自己常用的知识点总结下来,也将自己常犯的错误记录下来,于是慢慢成长!
经常有朋友私聊问我,如何才能快速提升技术水平?对于这样的问题,其实有时候很不想回答。其实,这跟上学没有什么太大的区别,还是要练、练、练,总结,总结,再总结。
大家不要觉得有什么捷径学习,还是脚踏实地地学习吧!
[[UIApplication sharedApplication] performSelector:@selector(suspend)];
suspend的英文意思有:暂停; 悬; 挂; 延缓;
大概举个例子,类似下面的URL,里面直接含有中文,可能导致播放不了,那么我们要处理一个这个URL,因为他太操蛋了,居然用中文。
// http://static.tripbe.com/videofiles/视频/我的自拍视频.mp4 NSString *path = (__bridge_transferNSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridgeCFStringRef)model.mp4_url, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
个人最常用的获取方法,感觉这个比较靠谱:
- (void)webViewDidFinishLoad:(UIWebView *)webView { CGFloat height = [[webViewstringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue]; CGRect frame = webView.frame; webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height); }
利用的UIView的设置背景颜色方法,用图片做图案颜色,然后传给背景颜色。
UIColor *bgColor = [UIColorcolorWithPatternImage: [UIImageimageNamed:@"bgImg.png"]; UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0,0,320,480)]; [myViewsetBackGroundColor:bgColor];
UIImage *image = [UIImageimageNamed:@"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。
yourTableView.tableFooterView = [UIView new];
- (void)viewDidLayoutSubviews { if ([self.mytableviewrespondsToSelector:@selector(setSeparatorInset:)]) { [self.mytableviewsetSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; } if ([self.mytableviewrespondsToSelector:@selector(setLayoutMargins:)]) { [self.mytableviewsetLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; } } #pragma mark - cell分割线 - (void)tableView:(UITableView *)tableViewwillDisplayCell:(UITableViewCell *)cellforRowAtIndexPath:(NSIndexPath *)indexPath { if ([cellrespondsToSelector:@selector(setSeparatorInset:)]){ [cellsetSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)]; } if ([cellrespondsToSelector:@selector(setLayoutMargins:)]) { [cellsetLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)]; } }
UILabel和UIImageView的交互userInteractionEabled默认为NO。那么如果你把这两个类做为父试图的话,里面的所有东东都不可以点击哦。
曾经有一个人,让我帮忙调试bug,他调试很久没搞定,就是把WMPlayer对象(播放器对象)放到一个UIImageView上面。这样imageView addSubView:wmPlayer 后,播放器的任何东东都不能点击了。userInteractionEabled设置为YES即可。
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { searchController.searchBar.showsCancelButton = YES; UIButton *canceLBtn = [searchController.searchBarvalueForKey:@"cancelButton"]; [canceLBtnsetTitle:@"取消"forState:UIControlStateNormal]; [canceLBtnsetTitleColor:[UIColorcolorWithRed:14.0/255.0green:180.0/255.0blue:0.0/255.0alpha:1.00]forState:UIControlStateNormal]; searchBar.showsCancelButton = YES; return YES; }
一个属性搞定,效果好(UIScrollView同样可以使用) 以前是不是觉得[self.view endEditing:YES];很屌,这个下面的更屌。
yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
另外一个枚举为UIScrollViewKeyboardDismissModeInteractive,表示在键盘内部滑动,键盘逐渐下去。
经常有人在群里问:怎么改变VC的大小啊? 瞬间无语。(只有UIView才能设置大小,VC是控制器啊,哥!)
+ (UIColor *)colorWithHexString:(NSString *)color { NSString *cString = [[colorstringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]uppercaseString]; // String should be 6 or 8 characters if ([cStringlength] < 6) { return [UIColor clearColor]; } // strip 0X if it appears if ([cStringhasPrefix:@"0X"]) cString = [cStringsubstringFromIndex:2]; if ([cStringhasPrefix:@"#"]) cString = [cStringsubstringFromIndex:1]; if ([cStringlength] != 6) return [UIColor clearColor]; // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cStringsubstringWithRange:range]; //g range.location = 2; NSString *gString = [cStringsubstringWithRange:range]; //b range.location = 4; NSString *bString = [cStringsubstringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScannerscannerWithString:rString]scanHexInt:&r]; [[NSScannerscannerWithString:gString]scanHexInt:&g]; [[NSScannerscannerWithString:bString]scanHexInt:&b]; return [UIColorcolorWithRed:((float) r / 255.0f)green:((float) g / 255.0f)blue:((float) b / 255.0f)alpha:1.0f]; }
+ (NSString *)getweekDayStringWithDate:(NSDate *) date { NSCalendar * calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法 NSDateComponents *comps = [calendarcomponents:NSWeekdayCalendarUnitfromDate:date]; // 1 是周日,2是周一 3.以此类推 NSNumber * weekNumber = @([compsweekday]); NSInteger weekInt = [weekNumberintegerValue]; NSString *weekDayString = @"(周一)"; switch (weekInt) { case1: { weekDayString = @"(周日)"; } break; case2: { weekDayString = @"(周一)"; } break; case3: { weekDayString = @"(周二)"; } break; case4: { weekDayString = @"(周三)"; } break; case5: { weekDayString = @"(周四)"; } break; case6: { weekDayString = @"(周五)"; } break; case7: { weekDayString = @"(周六)"; } break; default: break; } return weekDayString; }
UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(120, 10, 80, 80)]; view2.backgroundColor = [UIColor redColor]; [self.viewaddSubview:view2]; UIBezierPath *maskPath = [UIBezierPathbezierPathWithRoundedRect:view2.boundsbyRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRightcornerRadii:CGSizeMake(10, 10)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init]; maskLayer.frame = view2.bounds; maskLayer.path = maskPath.CGPath; view2.layer.mask = maskLayer; //其中,byRoundingCorners:UIRectCornerBottomLeft |UIRectCornerBottomRight //指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有: * UIRectCornerTopLeft * UIRectCornerTopRight * UIRectCornerBottomLeft * UIRectCornerBottomRight * UIRectCornerAllCorners
从名字很容易看出来代表的意思,使用“|”来组合就好了。
navigationController.hidesBarsOnSwipe = Yes;
记得先 QuartzCore框架的导入
#import <QuartzCore/QuartzCore.h> CGContextRef context =UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].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);
需要设置其preferredMaxLayoutWidth属性才能正常显示多行内容。另外如果出现显示不全文本,可以在计算的结果基础上+0.5。
CGFloat h = [model.messageboundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOriginattributes:attributescontext:nil].size.height+0.5;
[[UIApplication sharedApplication]setIdleTimerDisabled:YES];
KVC同时还提供了很复杂的函数,主要有下面这些
简单集合运算符共有@avg, @count , @max , @min ,@sum5种,都表示啥不用我说了吧, 目前还不支持自定义。
@interfaceBook: NSObject @property (nonatomic,copy) NSString* name; @property (nonatomic,assign) CGFloat price; @end @implementation Book @end Book *book1 = [Book new]; book1.name = @"The Great Gastby"; book1.price = 22; Book *book2 = [Book new]; book2.name = @"Time History"; book2.price = 12; Book *book3 = [Book new]; book3.name = @"Wrong Hole"; book3.price = 111; Book *book4 = [Book new]; book4.name = @"Wrong Hole"; book4.price = 111; NSArray* arrBooks = @[book1,book2,book3,book4]; NSNumber* sum = [arrBooksvalueForKeyPath:@"@sum.price"]; NSLog(@"sum:%f",sum.floatValue); NSNumber* avg = [arrBooksvalueForKeyPath:@"@avg.price"]; NSLog(@"avg:%f",avg.floatValue); NSNumber* count = [arrBooksvalueForKeyPath:@"@count"]; NSLog(@"count:%f",count.floatValue); NSNumber* min = [arrBooksvalueForKeyPath:@"@min.price"]; NSLog(@"min:%f",min.floatValue); NSNumber* max = [arrBooksvalueForKeyPath:@"@max.price"]; NSLog(@"max:%f",max.floatValue);
2016-04-20 16:45:54.696 KVCDemo[1484:127089]sum:256.000000 2016-04-20 16:45:54.697 KVCDemo[1484:127089]avg:64.000000 2016-04-20 16:45:54.697 KVCDemo[1484:127089]count:4.000000 2016-04-20 16:45:54.697 KVCDemo[1484:127089]min:12.000000 NSArray 快速求总和 最大值 最小值 和 平均值
NSArray *array = [NSArrayarrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil]; CGFloat sum = [[arrayvalueForKeyPath:@"@sum.floatValue"]floatValue]; CGFloat avg = [[arrayvalueForKeyPath:@"@avg.floatValue"]floatValue]; CGFloat max =[[arrayvalueForKeyPath:@"@max.floatValue"]floatValue]; CGFloat min =[[arrayvalueForKeyPath:@"@min.floatValue"]floatValue]; NSLog(@"%f/n%f/n%f/n%f",sum,avg,max,min);
尽量不要加到UIWindow上,加self.view上即可。如果加UIWindow上在iPad上,旋转屏幕的时候MBProgressHud不会旋转。之前有人遇到这个bug,我让他改放到self.view上即可解决此bug。
- (void)exitApplication { AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIViewanimateWithDuration:1.0fanimations:^{ window.alpha = 0; }completion:^(BOOL finished) { exit(0); }]; }
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:self.contentLabel.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init]; [paragraphStylesetLineSpacing:3]; //调整行间距 [attributedStringaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.contentLabel.textlength])]; self.contentLabel.attributedText = attributedString;
podinstall –verbose –no-repo-update podupdate –verbose –no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。
在XCode中targets的build phases选项下Compile Sources下选择->不需要arc编译的文件,双击输入 -fno-objc-arc 即可
MRC工程中也可以使用ARC的类,方法如下:
在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件,双击输入 -fobjc-arc 即可
_yourTableView.tintColor = [UIColor redColor];
[buttonsetExclusiveTouch:YES];
textField.placeholder = @"请输入用户名"; [textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"]; [textFieldsetValue:[UIFontboldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];
- (BOOL)canPerformAction:(SEL)actionwithSender:(id)sender { if ([UIMenuController sharedMenuController]) { [UIMenuController sharedMenuController].menuVisible = NO; } return NO; }
先用iTunes Link Maker找到软件在访问地址,格式为itms-apps://ax.itunes.apple.com/…,然后复制链接!
#define ITUNESLINK @"itms-apps://ax.itunes.apple.com/..." NSURL *url = [NSURLURLWithString:ITUNESLINK]; if([[UIApplication sharedApplication]canOpenURL:url]){ [[UIApplication sharedApplication]openURL:url]; }
如果把上述地址中itms-apps改为http就可以在浏览器中打开了。可以把这个地址放在自己的网站里,链接到app store。 iTunes Link Maker地址: http://itunes.apple.com/linkmaker
二级、三级界面隐藏系统tabbar方法.
YourViewController *yourVC = [YourViewController new]; yourVC.hidesBottomBarWhenPushed = YES; [self.navigationControllerpushViewController:yourVCanimated:YES];
新建一个类BaseNavigationController继承UINavigationController,然后重写 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated这个方法。所有的push事件都走此方法。
@interfaceBaseNavigationController: UINavigationController @end -(void)pushViewController:(UIViewController *)viewControlleranimated:(BOOL)animated{ [superpushViewController:viewControlleranimated:animated]; if (self.viewControllers.count>1) { viewController.hidesBottomBarWhenPushed = YES; } }
一行代码搞定:
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
UIWebView设置字体大小,颜色,字体: UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置 在webView加载完毕后:
- (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'"; [webViewstringByEvaluatingJavaScriptFromString:str]; }
或者加入以下代码
NSString *jsString = [[NSString alloc]initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor]; [webViewstringByEvaluatingJavaScriptFromString:jsString];
版本声明:本文由标哥的技术博客转载自 http://blog.csdn.net/wenmingzheng/article/details/52180380