[UIApplicationsharedApplication].idleTimerDisabled=YES;2、隐藏某行cell
-(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath{//如果是你需要隐藏的那一行,返回高度为0if(indexPath.row==YouWantToHideRow)return0;return44;}//然后再你需要隐藏cell的时候调用[self.tableViewbeginUpdates];[self.tableViewendUpdates];3、禁用button高亮
button.adjustsImageWhenHighlighted=NO;或者在创建的时候UIButton*button=[UIButtonbuttonWithType:UIButtonTypeCustom];4、tableview遇到这种报错failedtoobtainacellfromitsdataSource
是因为你的cell被调用的早了。先循环使用了cell,后又创建cell。顺序错了
可能原因:1、xib的cell没有注册2、内存中已经有这个cell的缓存了(也就是说通过你的cellId找到的cell并不是你想要的类型),这时候需要改下cell的标识
解决办法:原因可能是网络问题,网络请求超时了,只需要重试就行了
6、cocoapods出现ERROR:Whileexecutinggem...(Errno::EPERM)
解决办法:
7、动画切换window的根控制器
//options是动画选项[UIViewtransitionWithView:[UIApplicationsharedApplication].keyWindowduration:0.5foptions:UIViewAnimationOptionTransitionCrossDissolveanimations:^{BOOLoldState=[UIViewareAnimationsEnabled];[UIViewsetAnimationsEnabled:NO];[UIApplicationsharedApplication].keyWindow.rootViewController=[RootViewControllernew];[UIViewsetAnimationsEnabled:oldState];}completion:^(BOOLfinished){}];8、去除数组中重复的对象
NSArray*newArr=[oldArrvalueForKeyPath:@“@distinctUnionOfObjects.self"];9、编译的时候遇到nosuchfileordirectory:/users/apple/XXX
是因为编译的时候,在此路径下找不到这个文件,解决这个问题,首先是是要检查缺少的文件是不是在工程中,如果不在工程中,需要从本地拖进去,如果发现已经存在工程中了,或者拖进去还是报错,这时候需要去buildphases中搜索这个文件,这时候很可能会搜出现两个相同的文件,这时候,有一个路径是正确的,删除另外一个即可。如果删除了还是不行,需要把两个都删掉,然后重新往工程里拖进这个文件即可
10、iOS8系统中,tableView最好实现下-tableView:heightForRowAtIndexPath:这个代理方法,要不然在iOS8中可能就会出现显示不全或者无法响应事件的问题
11、iOS8中实现侧滑功能的时候这个方法必须实现,要不然在iOS8中无法侧滑
//必须写的方法,和editActionsForRowAtIndexPath配对使用,里面什么不写也行-(void)tableView:(UITableView*)tableViewcommitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath*)indexPath{}12、三个通知
13、SDWebImage本地缓存有时候会害人。如果之前缓存过一张图片,即使下次服务器换了这张图片,但是图片url没换,用sdwebimage下载下来的还是以前那张,所以遇到这种问题,不要先去怼服务器,清空下缓存再试就好了。
14、上线前注意:
15、跳进app权限设置
//跳进app设置if(UIApplicationOpenSettingsURLString!=NULL){NSURL*url=[NSURLURLWithString:UIApplicationOpenSettingsURLString];[[UIApplicationsharedApplication]openURL:url];}}16、给一个view截图
UIGraphicsBeginImageContextWithOptions(view.bounds.size,YES,0.0);[view.layerrenderInContext:UIGraphicsGetCurrentContext()];UIImage*img=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();17、开发中如果要动态修改tableView的tableHeaderView或者tableFooterView的高度,需要给tableView重新设置,而不是直接更改高度。正确的做法是重新设置一下tableView.tableFooterView=更改过高度的view。为什么?其实在iOS8以上直接改高度是没有问题的,在iOS8中出现了contentSize不准确的问题,这是解决办法。
18、注意对象为nil的时候,调用此对象分类的方法不会执行
19、collectionView的内容小于其宽高的时候是不能滚动的,设置可以滚动:
collectionView.alwaysBounceHorizontal=YES;collectionView.alwaysBounceVertical=YES;20、设置navigationBar上的title颜色和大小
[self.navigationController.navigationBarsetTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColoryouColor],NSFontAttributeName:[UIFontsystemFontOfSize:15]}]21、颜色转图片
+(UIImage*)cl_imageWithColor:(UIColor*)color{CGRectrect=CGRectMake(0.0f,0.0f,1.0f,1.0f);UIGraphicsBeginImageContext(rect.size);CGContextRefcontext=UIGraphicsGetCurrentContext();CGContextSetFillColorWithColor(context,[colorCGColor]);CGContextFillRect(context,rect);UIImage*image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnimage;}22、view设置圆角
#defineViewBorderRadius(View,Radius,Width,Color)\\[View.layersetCornerRadius:(Radius)];\[View.layersetMasksToBounds:YES];\[View.layersetBorderWidth:(Width)];\[View.layersetBorderColor:[ColorCGColor]]//view圆角23、强/弱引用
#defineWeakSelf(type)__weaktypeof(type)weak##type=type;//weak#defineStrongSelf(type)__strongtypeof(type)type=weak##type;//strong24、由角度转换弧度
#defineDegreesToRadian(x)(M_PI*(x)/180.0)25、由弧度转换角度
#defineRadianToDegrees(radian)(radian*180.0)/(M_PI)26、获取图片资源
#defineGetImage(imageName)[UIImageimageNamed:[NSStringstringWithFormat:@"%@",imageName]]27、获取temp
#definePathTempNSTemporaryDirectory()28、获取沙盒Document
#definePathDocument[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)firstObject]29、获取沙盒Cache
#definePathCache[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject]30、GCD代码只执行一次
#definekDISPATCH_ONCE_BLOCK(onceBlock)staticdispatch_once_tonceToken;dispatch_once(&onceToken,onceBlock);31、自定义NSLog
#ifdefDEBUG#defineNSLog(fmt,...)NSLog((@"%s[Line%d]"fmt),__PRETTY_FUNCTION__,__LINE__,##__VA_ARGS__)#else#defineNSLog(...)#endif32、Font
#defineFontL(s)[UIFontsystemFontOfSize:sweight:UIFontWeightLight]#defineFontR(s)[UIFontsystemFontOfSize:sweight:UIFontWeightRegular]#defineFontB(s)[UIFontsystemFontOfSize:sweight:UIFontWeightBold]#defineFontT(s)[UIFontsystemFontOfSize:sweight:UIFontWeightThin]#defineFont(s)FontL(s)33、FORMAT
#defineFORMAT(f,...)[NSStringstringWithFormat:f,##__VA_ARGS__]34、在主线程上运行
#definekDISPATCH_MAIN_THREAD(mainQueueBlock)dispatch_async(dispatch_get_main_queue(),mainQueueBlock);35、开启异步线程
#definekDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock)dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),globalQueueBlocl);36、通知
#defineNOTIF_ADD(n,f)[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(f)name:nobject:nil]#defineNOTIF_POST(n,o)[[NSNotificationCenterdefaultCenter]postNotificationName:nobject:o]#defineNOTIF_REMV()[[NSNotificationCenterdefaultCenter]removeObserver:self]37、随机颜色
+(UIColor*)RandomColor{NSIntegeraRedValue=arc4random()%255;NSIntegeraGreenValue=arc4random()%255;NSIntegeraBlueValue=arc4random()%255;UIColor*randColor=[UIColorcolorWithRed:aRedValue/255.0fgreen:aGreenValue/255.0fblue:aBlueValue/255.0falpha:1.0f];returnrandColor;}38、获取window
+(UIWindow*)getWindow{UIWindow*win=nil;//[UIApplicationsharedApplication].keyWindow;for(iditemin[UIApplicationsharedApplication].windows){if([itemclass]==[UIWindowclass]){if(!((UIWindow*)item).hidden){win=item;break;}}}returnwin;}39、修改textField的placeholder的字体颜色、大小
[textFieldsetValue:[UIColorredColor]forKeyPath:@"_placeholderLabel.textColor"];[textFieldsetValue:[UIFontboldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];40、统一收起键盘
[[[UIApplicationsharedApplication]keyWindow]endEditing:YES];41、控制屏幕旋转,在控制器中写
/**是否支持自动转屏*/-(BOOL)shouldAutorotate{returnYES;}/**支持哪些屏幕方向*/-(UIInterfaceOrientationMask)supportedInterfaceOrientations{returnUIInterfaceOrientationMaskLandscapeLeft|UIInterfaceOrientationMaskLandscapeRight;}/**默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法)*/-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{returnUIInterfaceOrientationLandscapeLeft|UIInterfaceOrientationLandscapeRight;}42、获取app缓存大小
-(CGFloat)getCachSize{NSUIntegerimageCacheSize=[[SDImageCachesharedImageCache]getSize];//获取自定义缓存大小//用枚举器遍历一个文件夹的内容//1.获取文件夹枚举器NSString*myCachePath=[NSHomeDirectory()stringByAppendingPathComponent:@"Library/Caches"];NSDirectoryEnumerator*enumerator=[[NSFileManagerdefaultManager]enumeratorAtPath:myCachePath];__blockNSUIntegercount=0;//2.遍历for(NSString*fileNameinenumerator){NSString*path=[myCachePathstringByAppendingPathComponent:fileName];NSDictionary*fileDict=[[NSFileManagerdefaultManager]attributesOfItemAtPath:patherror:nil];count+=fileDict.fileSize;//自定义所有缓存大小}//得到是字节转化为MCGFloattotalSize=((CGFloat)imageCacheSize+count)/1024/1024;returntotalSize;}43、清理app缓存
-(void)handleClearView{//删除两部分//1.删除sd图片缓存//先清除内存中的图片缓存[[SDImageCachesharedImageCache]clearMemory];//清除磁盘的缓存[[SDImageCachesharedImageCache]clearDisk];//2.删除自己缓存NSString*myCachePath=[NSHomeDirectory()stringByAppendingPathComponent:@"Library/Caches"];[[NSFileManagerdefaultManager]removeItemAtPath:myCachePatherror:nil];}44、模型转字典
ClassaClass=[selfclass];SELoriginalSelector=@selector(viewWillAppear:);SELswizzledSelector=@selector(xxx_viewWillAppear:);MethodoriginalMethod=class_getInstanceMethod(aClass,originalSelector);MethodswizzledMethod=class_getInstanceMethod(aClass,swizzledSelector);BOOLdidAddMethod=class_addMethod(aClass,originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod));if(didAddMethod){class_replaceMethod(aClass,swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));}else{method_exchangeImplementations(originalMethod,swizzledMethod);}46、打印百分号和引号
NSLog(@"%%");NSLog(@"\"");47、几个常用权限判断
if([CLLocationManagerauthorizationStatus]==kCLAuthorizationStatusDenied){NSLog(@"没有定位权限");}AVAuthorizationStatusstatusVideo=[AVCaptureDeviceauthorizationStatusForMediaType:AVMediaTypeVideo];if(statusVideo==AVAuthorizationStatusDenied){NSLog(@"没有摄像头权限");}//是否有麦克风权限AVAuthorizationStatusstatusAudio=[AVCaptureDeviceauthorizationStatusForMediaType:AVMediaTypeAudio];if(statusAudio==AVAuthorizationStatusDenied){NSLog(@"没有录音权限");}[PHPhotoLibraryrequestAuthorization:^(PHAuthorizationStatusstatus){if(status==PHAuthorizationStatusDenied){NSLog(@"没有相册权限");}}];48、获取手机型号
-(void)viewDidLoad{[self.viewaddGestureRecognizer:[[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(pasteBoard:)]];}-(void)pasteBoard:(UILongPressGestureRecognizer*)longPress{if(longPress.state==UIGestureRecognizerStateBegan){UIPasteboard*pasteboard=[UIPasteboardgeneralPasteboard];pasteboard.string=@"需要复制的文本";}}50、cocoapods升级
在终端执行sudogeminstall-n/usr/local/bincocoapods--pre
51、设置启动页后,依然显示之前的
删除app,手机重启,重新安装
52、判断图片类型
//通过图片Data数据第一个字节来获取图片扩展名-(NSString*)contentTypeForImageData:(NSData*)data{uint8_tc;[datagetBytes:&clength:1];switch(c){case0xFF:return@"jpeg";case0x89:return@"png";case0x47:return@"gif";case0x49:case0x4D:return@"tiff";case0x52:if([datalength]<12){returnnil;}NSString*testString=[[NSStringalloc]initWithData:[datasubdataWithRange:NSMakeRange(0,12)]encoding:NSASCIIStringEncoding];if([testStringhasPrefix:@"RIFF"]&&[testStringhasSuffix:@"WEBP"]){return@"webp";}returnnil;}returnnil;}53、获取手机和app信息
idLenderClass=objc_getClass("Lender");unsignedintoutCount,i;objc_property_t*properties=class_copyPropertyList(LenderClass,&outCount);for(i=0;i -(UIImage*)circleImage{//NO代表透明UIGraphicsBeginImageContextWithOptions(self.size,NO,1);//获得上下文CGContextRefctx=UIGraphicsGetCurrentContext();//添加一个圆CGRectrect=CGRectMake(0,0,self.size.width,self.size.height);//方形变圆形CGContextAddEllipseInRect(ctx,rect);//裁剪CGContextClip(ctx);//将图片画上去[selfdrawInRect:rect];UIImage*image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnimage;}56、image拉伸 +(UIImage*)resizableImage:(NSString*)imageName{UIImage*image=[UIImageimageNamed:imageName];CGFloatimageW=image.size.width;CGFloatimageH=image.size.height;return[imageresizableImageWithCapInsets:UIEdgeInsetsMake(imageH*0.5,imageW*0.5,imageH*0.5,imageW*0.5)resizingMode:UIImageResizingModeStretch];}57、JSON字符串转字典 +(NSDictionary*)parseJSONStringToNSDictionary:(NSString*)JSONString{NSData*JSONData=[JSONStringdataUsingEncoding:NSUTF8StringEncoding];NSDictionary*responseJSON=[NSJSONSerializationJSONObjectWithData:JSONDataoptions:NSJSONReadingMutableLeaveserror:nil];returnresponseJSON;}58、身份证号验证 -(BOOL)validateIdentityCard{BOOLflag;if(self.length<=0){flag=NO;returnflag;}NSString*regex2=@"^(\\d{14}|\\d{17})(\\d|[xX])$";NSPredicate*identityCardPredicate=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",regex2];return[identityCardPredicateevaluateWithObject:self];}59、获取设备mac地址 +(NSString*)macAddress{intmib[6];size_tlen;char*buf;unsignedchar*ptr;structif_msghdr*ifm;structsockaddr_dl*sdl;mib[0]=CTL_NET;mib[1]=AF_ROUTE;mib[2]=0;mib[3]=AF_LINK;mib[4]=NET_RT_IFLIST;if((mib[5]=if_nametoindex("en0"))==0){printf("Error:if_nametoindexerror\n");returnNULL;}if(sysctl(mib,6,NULL,&len,NULL,0)<0){printf("Error:sysctl,take1\n");returnNULL;}if((buf=malloc(len))==NULL){printf("Couldnotallocatememory.Rrror!\n");returnNULL;}if(sysctl(mib,6,buf,&len,NULL,0)<0){printf("Error:sysctl,take2");returnNULL;}ifm=(structif_msghdr*)buf;sdl=(structsockaddr_dl*)(ifm+1);ptr=(unsignedchar*)LLADDR(sdl);NSString*outstring=[NSStringstringWithFormat:@"X:X:X:X:X:X",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5)];free(buf);returnoutstring;}60、导入自定义字体库 61、拿到当前正在显示的控制器,不管是push进去的,还是present进去的都能拿到 -(UIViewController*)getVisibleViewControllerFrom:(UIViewController*)vc{if([vcisKindOfClass:[UINavigationControllerclass]]){return[selfgetVisibleViewControllerFrom:[((UINavigationController*)vc)visibleViewController]];}elseif([vcisKindOfClass:[UITabBarControllerclass]]){return[selfgetVisibleViewControllerFrom:[((UITabBarController*)vc)selectedViewController]];}else{if(vc.presentedViewController){return[selfgetVisibleViewControllerFrom:vc.presentedViewController];}else{returnvc;}}}62、runtime为一个类动态添加属性 //动态添加属性的本质是:让对象的某个属性与值产生关联objc_setAssociatedObject(self,WZBPlaceholderViewKey,placeholderView,OBJC_ASSOCIATION_RETAIN_NONATOMIC);63、获取runtime为一个类动态添加的属性 objc_getAssociatedObject(self,WZBPlaceholderViewKey);64、KVO监听某个对象的属性 //添加监听者[selfaddObserver:selfforKeyPath:propertyoptions:NSKeyValueObservingOptionNewcontext:nil];//当监听的属性值变化的时候会来到这个方法-(void)observeValueForKeyPath:(NSString*)keyPathofObject:(id)objectchange:(NSDictionary*)changecontext:(void*)context{if([keyPathisEqualToString:@"property"]){[selftextViewTextChange];}else{}}65、Reachability判断网络状态 NetworkStatusstatus=[[ReachabilityreachabilityForInternetConnection]currentReachabilityStatus];if(status==NotReachable){NSLog(@"当前设备无网络");}if(status==ReachableViaWiFi){NSLog(@"当前wifi网络");}if(status==NotReachable){NSLog(@"当前蜂窝移动网络");}66、AFNetworking监听网络状态 //监听网络状况AFNetworkReachabilityManager*mgr=[AFNetworkReachabilityManagersharedManager];[mgrsetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus){switch(status){caseAFNetworkReachabilityStatusUnknown:break;caseAFNetworkReachabilityStatusNotReachable:{[SVProgressHUDshowInfoWithStatus:@"当前设备无网络"];}break;caseAFNetworkReachabilityStatusReachableViaWiFi:[SVProgressHUDshowInfoWithStatus:@"当前Wi-Fi网络"];break;caseAFNetworkReachabilityStatusReachableViaWWAN:[SVProgressHUDshowInfoWithStatus:@"当前蜂窝移动网络"];break;default:break;}}];[mgrstartMonitoring];67、透明颜色不影响子视图透明度 [UIColorcolorWithRed:green:blue:alpha:];68、取图片某一点的颜色 -(BOOL)hasAlphaChannel{CGImageAlphaInfoalpha=CGImageGetAlphaInfo(self.CGImage);return(alpha==kCGImageAlphaFirst||alpha==kCGImageAlphaLast||alpha==kCGImageAlphaPremultipliedFirst||alpha==kCGImageAlphaPremultipliedLast);}70、获得灰度图 +(UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage{intwidth=sourceImage.size.width;intheight=sourceImage.size.height;CGColorSpaceRefcolorSpace=CGColorSpaceCreateDeviceGray();CGContextRefcontext=CGBitmapContextCreate(nil,width,height,8,0,colorSpace,kCGImageAlphaNone);CGColorSpaceRelease(colorSpace);if(context==NULL){returnnil;}CGContextDrawImage(context,CGRectMake(0,0,width,height),sourceImage.CGImage);CGImageRefcontextRef=CGBitmapContextCreateImage(context);UIImage*grayImage=[UIImageimageWithCGImage:contextRef];CGContextRelease(context);CGImageRelease(contextRef);returngrayImage;}71、根据bundle中的文件名读取图片 +(UIImage*)imageWithFileName:(NSString*)name{NSString*extension=@"png";NSArray*components=[namecomponentsSeparatedByString:@"."];if([componentscount]>=2){NSUIntegerlastIndex=components.count-1;extension=[componentsobjectAtIndex:lastIndex];name=[namesubstringToIndex:(name.length-(extension.length+1))];}//如果为Retina屏幕且存在对应图片,则返回Retina图片,否则查找普通图片if([UIScreenmainScreen].scale==2.0){name=[namestringByAppendingString:@"@2x"];NSString*path=[[NSBundlemainBundle]pathForResource:nameofType:extension];if(path!=nil){return[UIImageimageWithContentsOfFile:path];}}if([UIScreenmainScreen].scale==3.0){name=[namestringByAppendingString:@"@3x"];NSString*path=[[NSBundlemainBundle]pathForResource:nameofType:extension];if(path!=nil){return[UIImageimageWithContentsOfFile:path];}}NSString*path=[[NSBundlemainBundle]pathForResource:nameofType:extension];if(path){return[UIImageimageWithContentsOfFile:path];}returnnil;}72、合并两个图片 +(UIImage*)mergeImage:(UIImage*)firstImagewithImage:(UIImage*)secondImage{CGImageReffirstImageRef=firstImage.CGImage;CGFloatfirstWidth=CGImageGetWidth(firstImageRef);CGFloatfirstHeight=CGImageGetHeight(firstImageRef);CGImageRefsecondImageRef=secondImage.CGImage;CGFloatsecondWidth=CGImageGetWidth(secondImageRef);CGFloatsecondHeight=CGImageGetHeight(secondImageRef);CGSizemergedSize=CGSizeMake(MAX(firstWidth,secondWidth),MAX(firstHeight,secondHeight));UIGraphicsBeginImageContext(mergedSize);[firstImagedrawInRect:CGRectMake(0,0,firstWidth,firstHeight)];[secondImagedrawInRect:CGRectMake(0,0,secondWidth,secondHeight)];UIImage*image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();returnimage;}73、根据bundle中的图片名创建imageview +(id)imageViewWithImageNamed:(NSString*)imageName{return[[UIImageViewalloc]initWithImage:[UIImageimageNamed:imageName]];}74、为imageView添加倒影 CGRectframe=self.frame;frame.origin.y+=(frame.size.height+1);UIImageView*reflectionImageView=[[UIImageViewalloc]initWithFrame:frame];self.clipsToBounds=TRUE;reflectionImageView.contentMode=self.contentMode;[reflectionImageViewsetImage:self.image];reflectionImageView.transform=CGAffineTransformMakeScale(1.0,-1.0);CALayer*reflectionLayer=[reflectionImageViewlayer];CAGradientLayer*gradientLayer=[CAGradientLayerlayer];gradientLayer.bounds=reflectionLayer.bounds;gradientLayer.position=CGPointMake(reflectionLayer.bounds.size.width/2,reflectionLayer.bounds.size.height*0.5);gradientLayer.colors=[NSArrayarrayWithObjects:(id)[[UIColorclearColor]CGColor],(id)[[UIColorcolorWithRed:1.0green:1.0blue:1.0alpha:0.3]CGColor],nil];gradientLayer.startPoint=CGPointMake(0.5,0.5);gradientLayer.endPoint=CGPointMake(0.5,1.0);reflectionLayer.mask=gradientLayer;[self.superviewaddSubview:reflectionImageView];75、画水印 //画水印-(void)setImage:(UIImage*)imagewithWaterMark:(UIImage*)markinRect:(CGRect)rect{if([[[UIDevicecurrentDevice]systemVersion]floatValue]>=4.0){UIGraphicsBeginImageContextWithOptions(self.frame.size,NO,0.0);}//原图[imagedrawInRect:self.bounds];//水印图[markdrawInRect:rect];UIImage*newPic=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();self.image=newPic;}76、让label的文字内容显示在左上/右上/左下/右下/中心顶/中心底部 推荐用IQKeyboardManager这个框架!手动解决如下1、监听键盘弹出/消失的通知2、在通知中加入代码:NSDictionary*info=[aNotificationuserInfo];CGRectkeyPadFrame=[[UIApplicationsharedApplication].keyWindowconvertRect:[[infoobjectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue]fromView:self.view];CGSizekbSize=keyPadFrame.size;CGRectactiveRect=[self.viewconvertRect:activeField.framefromView:activeField.superview];CGRectaRect=self.view.bounds;aRect.size.height-=(kbSize.height);CGPointorigin=activeRect.origin;origin.y-=backScrollView.contentOffset.y;if(!CGRectContainsPoint(aRect,origin)){CGPointscrollPoint=CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));[backScrollViewsetContentOffset:scrollPointanimated:YES];}78、frame布局的cell动态高度 这种通常在你的模型中添加一个辅助属性cellHeight,在模型中重写这个属性的get方法,根据你的布局和模型中的其他属性值计算出总高度。最后在tableView:heightForRow方法中,根据indexPath找出对应的模型,返回这个高度即可。 79、AutoLayout布局的cell动态高度 cell 80、使用performSelector:调用函数,内存泄漏问题 当我们在开发中使用[objperformSelector:NSSelectorFromString(@"aMethod")];这类方法时可能会收到一个警告"performSelectormaycausealeakbecauseitsselectorisunknown". 是因为编译器不清楚这个对象能不能相应这个方法,如果不能,则是不安全的,而且编译器也不清楚该怎么处理这个方法的返回值! 使用以下代码调用即可:if(!obj){return;}SELselector=NSSelectorFromString(@"aMethod");IMPimp=[objmethodForSelector:selector];void(*func)(id,SEL)=(void*)imp;func(obj,selector);或者:SELselector=NSSelectorFromString(@"aMethod");((void(*)(id,SEL))[objmethodForSelector:selector])(obj,selector);81、一个字符串是否包含另一个字符串 //方法1if([str1containsString:str2]){NSLog(@"str1包含str2");}else{NSLog(@"str1不包含str2");}//方法2if([str1rangeOfString:str2].location==NSNotFound){NSLog(@"str1包含str2");}else{NSLog(@"str1不包含str2");}82、cell去除选中效果 cell.selectionStyle=UITableViewCellSelectionStyleNone;83、cell点按效果 -(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath{[tableViewdeselectRowAtIndexPath:indexPathanimated:YES];}84、当删除一个从xib拖出来的属性时,一定记得把xib中对应的线也删掉,不然会报类似[setValue:forUndefinedKey:]:thisclassisnotkeyvaluecoding-compliantforthekey的crash 点击这个叉号删除 85、真机测试的时候报错:Couldnotlaunch"你的App",processlaunchfailed:Security 因为你的app没有上线,iOS9开始,需要手动信任Xcode生成的描述文件,打开手机设置->通用->描述文件->点击你的app的描述文件->点击信任 86、真机测试的时候报错:CouldnotfindDeveloperDiskImage 这是因为你的设备系统版本大于Xcode能兼容的系统版本,比如你的设备是iOS10.3,而Xcode版本是8.2(Xcode8.2最大兼容iOS10.2),就会报这个错误。解决办法就是升级Xcode! 87、UITextView没有placeholder的问题? 网上有很多此类自定义控件,也可以参考下我写的一个UITextView分类UITextView-WZB 88、移除字符串中的空格和换行 +(NSString*)removeSpaceAndNewline:(NSString*)str{NSString*temp=[strstringByReplacingOccurrencesOfString:@""withString:@""];temp=[tempstringByReplacingOccurrencesOfString:@"\r"withString:@""];temp=[tempstringByReplacingOccurrencesOfString:@"\n"withString:@""];returntemp;}89、判断字符串中是否有空格 +(BOOL)isBlank:(NSString*)str{NSRange_range=[strrangeOfString:@""];if(_range.location!=NSNotFound){//有空格returnYES;}else{//没有空格returnNO;}}90、获取一个视频的第一帧图片 NSURL*url=[NSURLURLWithString:filepath];AVURLAsset*asset1=[[AVURLAssetalloc]initWithURL:urloptions:nil];AVAssetImageGenerator*generate1=[[AVAssetImageGeneratoralloc]initWithAsset:asset1];generate1.appliesPreferredTrackTransform=YES;NSError*err=NULL;CMTimetime=CMTimeMake(1,2);CGImageRefoneRef=[generate1copyCGImageAtTime:timeactualTime:NULLerror:&err];UIImage*one=[[UIImagealloc]initWithCGImage:oneRef];returnone;91、获取视频的时长 +(NSInteger)getVideoTimeByUrlString:(NSString*)urlString{NSURL*videoUrl=[NSURLURLWithString:urlString];AVURLAsset*avUrl=[AVURLAssetassetWithURL:videoUrl];CMTimetime=[avUrlduration];intseconds=ceil(time.value/time.timescale);returnseconds;}92、字符串是否为空 +(BOOL)isEqualToNil:(NSString*)str{returnstr.length<=0||[strisEqualToString:@""]||!str;}93、将app上传到AppStore的时候通常会遇到这个问题 tryagain 很多人说这事苹果爸爸服务器问题,重复尝试几次,总会成功的! 但是经过尝试发现如果使用ApplicationLoader上传成功率就非常高,所以还是推荐把ipa文件导出直接用ApplicationLoader上传。 如果ApplicationLoader也不行,需要检查下自己的网络,有时候vpn也会提高速度。 94、当tableView占不满一屏时,去除下边多余的单元格 self.tableView.tableHeaderView=[UIViewnew];self.tableView.tableFooterView=[UIViewnew];95、isKindOfClass和isMemberOfClass的区别 isKindOfClass可以判断某个对象是否属于某个类,或者这个类的子类。isMemberOfClass更加精准,它只能判断这个对象类型是否为这个类(不能判断子类)96、__block 97、-[ViewControlleraMethod:]:unrecognizedselectorsenttoinstance0x7fe91e607fb0 这是一个经典错误,ViewController不能响应aMethod这个方法,错误原因可能viewController文件中没有实现aMethod这个方法 98、UITableView()failedtoobtainacellfromitsdataSource() 这个错误原因是tableView的代理方法-tableView:cellForRowAtIndexPath:需要返回一个UITableViewCell,而你返回了一个nil。另外这个地方返回值不是UITableViewCell类型也会导致崩溃 99、约束如何做UIView动画? @property(weak,nonatomic)IBOutletNSLayoutConstraint*buttonTopConstraint;self.buttonTopConstraint.constant=100;[UIViewanimateWithDuration:.5animations:^{[self.viewlayoutIfNeeded];}];100、从NSURL中拿到链接字符串 NSString*urlString=myURL.absoluteString;101、将tableView滚动到顶部 [tableViewsetContentOffset:CGPointZeroanimated:YES];或者[tableViewscrollRectToVisible:CGRectMake(0,0,1,1)animated:YES];102、如果用addTarget:action:forControlEvents:方法为一个button添加了很多点击事件,在某个时刻想一次删除怎么办?只需要调用下边这句代码 [youButtonremoveTarget:nilaction:nilforControlEvents:UIControlEventAllEvents];103、某个字体的高度 font.lineHeight;104、删除某个view所有的子视图 [[someViewsubviews]makeObjectsPerformSelector:@selector(removeFromSuperview)];105、删除NSUserDefaults所有记录 //方法一NSString*appDomain=[[NSBundlemainBundle]bundleIdentifier];[[NSUserDefaultsstandardUserDefaults]removePersistentDomainForName:appDomain];//方法二-(void)resetDefaults{NSUserDefaults*defs=[NSUserDefaultsstandardUserDefaults];NSDictionary*dict=[defsdictionaryRepresentation];for(idkeyindict){[defsremoveObjectForKey:key];}[defssynchronize];}//方法三[[NSUserDefaultsstandardUserDefaults]setPersistentDomain:[NSDictionarydictionary]forName:[[NSBundlemainBundle]bundleIdentifier]];106、禁用系统滑动返回功能 -(void)viewDidAppear:(BOOL)animated{[superviewDidAppear:animated];if([self.navigationControllerrespondsToSelector:@selector(interactivePopGestureRecognizer)]){self.navigationController.interactivePopGestureRecognizer.delegate=self;}}-(void)viewWillDisappear:(BOOL)animated{[superviewWillDisappear:animated];if([self.navigationControllerrespondsToSelector:@selector(interactivePopGestureRecognizer)]){self.navigationController.interactivePopGestureRecognizer.delegate=nil;}}-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer{returnNO;}107、模拟器报错 模拟器报错 打开模拟器->Simulator->ResetContentandSettings... 如果不行,就重启试试! 108、自定义cell选中背景颜色 UIView*bgColorView=[[UIViewalloc]init];bgColorView.backgroundColor=[UIColorredColor];[cellsetSelectedBackgroundView:bgColorView];109、UILabel设置内边距 子类化UILabel,重写drawTextInRect方法-(void)drawTextInRect:(CGRect)rect{//边距,上左下右UIEdgeInsetsinsets={0,5,0,5};[superdrawTextInRect:UIEdgeInsetsInsetRect(rect,insets)];}110、UILabel设置文字描边 子类化UILabel,重写drawTextInRect方法-(void)drawTextInRect:(CGRect)rect{CGContextRefc=UIGraphicsGetCurrentContext();//设置描边宽度CGContextSetLineWidth(c,1);CGContextSetLineJoin(c,kCGLineJoinRound);CGContextSetTextDrawingMode(c,kCGTextStroke);//描边颜色self.textColor=[UIColorredColor];[superdrawTextInRect:rect];//文本颜色self.textColor=[UIColoryellowColor];CGContextSetTextDrawingMode(c,kCGTextFill);[superdrawTextInRect:rect];}111、使用模拟器截图 快捷键command+s或者File->SaveScreenShot112、scrollView滚动到最下边 CGPointbottomOffset=CGPointMake(0,scrollView.contentSize.height-scrollView.bounds.size.height);[scrollViewsetContentOffset:bottomOffsetanimated:YES];113、UIView背景颜色渐变 UIView*view=[[UIViewalloc]initWithFrame:CGRectMake(0,0,320,100)];[self.viewaddSubview:view];CAGradientLayer*gradient=[CAGradientLayerlayer];gradient.frame=view.bounds;gradient.colors=[NSArrayarrayWithObjects:(id)[[UIColorblackColor]CGColor],(id)[[UIColorwhiteColor]CGColor],nil];[view.layerinsertSublayer:gradientatIndex:0];114、停止UIView动画 [yourView.layerremoveAllAnimations]115、为UIView某个角添加圆角 //左上角和右下角添加圆角UIBezierPath*maskPath=[UIBezierPathbezierPathWithRoundedRect:view.boundsbyRoundingCorners:(UIRectCornerTopLeft|UIRectCornerBottomRight)cornerRadii:CGSizeMake(20,20)];CAShapeLayer*maskLayer=[CAShapeLayerlayer];maskLayer.frame=view.bounds;maskLayer.path=maskPath.CGPath;view.layer.mask=maskLayer;116、删除XcodeDeriveddata缓存数据 依次点击Xcode->Preferences->location,然后点击Deriveddata路径后到小箭头,删除这个文件夹下的数据就可以了,如图 XcodeDeriveddata 117、将一个view放置在其兄弟视图的最上面 [parentViewbringSubviewToFront:yourView]118、将一个view放置在其兄弟视图的最下面 [parentViewsendSubviewToBack:yourView]119、让手机震动一下 倒入框架#importAudioServicesPlayAlertSound(kSystemSoundID_Vibrate);或者AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);120、layoutSubviews方法什么时候调用? 121、让UILabel在指定的地方换行 //换行符为\n,在需要换行的地方加上这个符号即可,如label.numberOfLines=0;label.text=@"此处\n换行";122、摇一摇功能 1、打开摇一摇功能[UIApplicationsharedApplication].applicationSupportsShakeToEdit=YES;2、让需要摇动的控制器成为第一响应者[selfbecomeFirstResponder];3、实现以下方法//开始摇动-(void)motionBegan:(UIEventSubtype)motionwithEvent:(UIEvent*)event//取消摇动-(void)motionCancelled:(UIEventSubtype)motionwithEvent:(UIEvent*)event//摇动结束-(void)motionEnded:(UIEventSubtype)motionwithEvent:(UIEvent*)event123、获取图片大小 CGFloatimageWidth=image.size.width;CGFloatimageHeight=imageWidth*image.scale;124、获取view的坐标在整个window上的位置 //v上的(0,0)点在toView上的位置CGPointpoint=[vconvertPoint:CGPointMake(0,0)toView:[UIApplicationsharedApplication].windows.lastObject];或者CGPointpoint=[v.superviewconvertPoint:v.frame.origintoView:[UIApplicationsharedApplication].windows.lastObject];125、提交AppStore审核程序限制 126、修改UISegmentedControl的字体大小 [segmentsetTitleTextAttributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:15.0f]}forState:UIControlStateNormal];127、在非ViewController的地方弹出UIAlertController对话框 //最好抽成一个分类UIAlertController*alertController=[UIAlertControlleralertControllerWithTitle:@"Title"message:@"message"preferredStyle:UIAlertControllerStyleAlert];//...idrootViewController=[UIApplicationsharedApplication].delegate.window.rootViewController;if([rootViewControllerisKindOfClass:[UINavigationControllerclass]]){rootViewController=((UINavigationController*)rootViewController).viewControllers.firstObject;}if([rootViewControllerisKindOfClass:[UITabBarControllerclass]]){rootViewController=((UITabBarController*)rootViewController).selectedViewController;}[rootViewControllerpresentViewController:alertControlleranimated:YEScompletion:nil];128、获取一个view所属的控制器 //view分类方法-(UIViewController*)belongViewController{for(UIView*next=[selfsuperview];next;next=next.superview){UIResponder*nextResponder=[nextnextResponder];if([nextResponderisKindOfClass:[UIViewControllerclass]]){return(UIViewController*)nextResponder;}}returnnil;}129、UIImage和base64互转 //view分类方法-(NSString*)encodeToBase64String:(UIImage*)image{return[UIImagePNGRepresentation(image)base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];}-(UIImage*)decodeBase64ToImage:(NSString*)strEncodeData{NSData*data=[[NSDataalloc]initWithBase64EncodedString:strEncodeDataoptions:NSDataBase64DecodingIgnoreUnknownCharacters];return[UIImageimageWithData:data];}130、UIWebView设置背景透明 [webViewsetBackgroundColor:[UIColorclearColor]];[webViewsetOpaque:NO];131、判断NSDate是不是今天 NSDateComponents*otherDay=[[NSCalendarcurrentCalendar]components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:aDate];NSDateComponents*today=[[NSCalendarcurrentCalendar]components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDayfromDate:[NSDatedate]];if([todayday]==[otherDayday]&&[todaymonth]==[otherDaymonth]&&[todayyear]==[otherDayyear]&&[todayera]==[otherDayera]){//是今天}132、设置tableView分割线颜色 [self.tableViewsetSeparatorColor:[UIColormyColor]];133、设置屏幕方向 [[UIDevicecurrentDevice]setValue:@(UIInterfaceOrientationLandscapeLeft)forKey:@"orientation"];134、比较两个颜色是否相等 -(BOOL)isEqualToColor:(UIColor*)otherColor{CGColorSpaceRefcolorSpaceRGB=CGColorSpaceCreateDeviceRGB();6UIColor*(^convertColorToRGBSpace)(UIColor*)=^(UIColor*color){if(CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor))==kCGColorSpaceModelMonochrome){constCGFloat*oldComponents=CGColorGetComponents(color.CGColor);CGFloatcomponents[4]={oldComponents[0],oldComponents[0],oldComponents[0],oldComponents[1]};CGColorRefcolorRef=CGColorCreate(colorSpaceRGB,components);6UIColor*color=[UIColorcolorWithCGColor:colorRef];CGColorRelease(colorRef);returncolor;}elsereturncolor;};6UIColor*selfColor=convertColorToRGBSpace(self);otherColor=convertColorToRGBSpace(otherColor);CGColorSpaceRelease(colorSpaceRGB);return[selfColorisEqual:otherColor];}135、tableViewCell分割线顶到头 -(void)tableView:(UITableView*)tableViewwillDisplayCell:(UITableViewCell*)cellforRowAtIndexPath:(NSIndexPath*)indexPath{[cellsetSeparatorInset:UIEdgeInsetsZero];[cellsetLayoutMargins:UIEdgeInsetsZero];cell.preservesSuperviewLayoutMargins=NO;}-(void)viewDidLayoutSubviews{[self.tableViewsetSeparatorInset:UIEdgeInsetsZero];[self.tableViewsetLayoutMargins:UIEdgeInsetsZero];}136、不让控制器的view随着控制器的xib拉伸或压缩 Youcantryaddingitmanuallyin~/.cocoapods/reposorviapodrepoadd. 解决方法:这是因为电脑里安装了另外一个Xcode导致cocoapods找不到路径了 在终端执行sudoxcode-select-switch/Applications/Xcode.app即可 138、安装cocoapods的时候出现ERROR:Whileexecutinggem...(Errno::EPERM) Operationnotpermitted-/usr/bin/pod解决办法:直接在终端执行sudogeminstall-n/usr/local/bincocoapods 139、在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花 [UIApplicationsharedApplication].networkActivityIndicatorVisible=YES;140、检查一个rect是否包含一个point //point是否在rect内BOOLisContains=CGRectContainsPoint(rect,point);141、在指定的宽度下,让UILabel自动设置最佳font label.adjustsFontSizeToFitWidth=YES;142、将一个image保存在相册中 UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);或者#import[[PHPhotoLibrarysharedPhotoLibrary]performChanges:^{PHAssetChangeRequest*changeRequest=[PHAssetChangeRequestcreationRequestForAssetFromImage:image];changeRequest.creationDate=[NSDatedate];}completionHandler:^(BOOLsuccess,NSError*error){if(success){NSLog(@"successfullysaved");}else{NSLog(@"errorsavingtophotos:%@",error);}}];143、修改cell.imageView的大小 UIImage*icon=[UIImageimageNamed:@""];CGSizeitemSize=CGSizeMake(30,30);UIGraphicsBeginImageContextWithOptions(itemSize,NO,0.0);CGRectimageRect=CGRectMake(0.0,0.0,itemSize.width,itemSize.height);[icondrawInRect:imageRect];cell.imageView.image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();144、为一个view添加虚线边框 CAShapeLayer*border=[CAShapeLayerlayer];border.strokeColor=[UIColorcolorWithRed:67/255.0fgreen:37/255.0fblue:83/255.0falpha:1].CGColor;border.fillColor=nil;border.lineDashPattern=@[@4,@2];border.path=[UIBezierPathbezierPathWithRect:view.bounds].CGPath;border.frame=view.bounds;[view.layeraddSublayer:border];