您的位置:首页 > 移动开发 > IOS开发

iOS 知识 - 常用小技巧大杂烩 - 转载

2016-09-01 15:41 471 查看
1,打印View所有子视图

po[[selfview]recursiveDescription]

2,layoutSubviews调用的调用时机

*当视图第一次显示的时候会被调用。
*添加子视图也会调用这个方法。
*当本视图的大小发生改变的时候是会调用的。
*当子视图的frame发生改变的时候是会调用的。
*当删除子视图的时候是会调用的.

3,NSString过滤特殊字符

//定义一个特殊字符的集合
NSCharacterSet*set=[NSCharacterSetcharacterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
//过滤字符串的特殊字符
NSString*newString=[trimStringstringByTrimmingCharactersInSet:set];

4,TransForm属性

//平移按钮
CGAffineTransformtransForm=self.buttonView.transform;
self.buttonView.transform=CGAffineTransformTranslate(transForm,10,0);

//旋转按钮
CGAffineTransformtransForm=self.buttonView.transform;
self.buttonView.transform=CGAffineTransformRotate(transForm,M_PI_4);

//缩放按钮
self.buttonView.transform=CGAffineTransformScale(transForm,1.2,1.2);

//初始化复位
self.buttonView.transform=CGAffineTransformIdentity;

5,去掉分割线多余15像素

首先在viewDidLoad方法加入以下代码:
if([self.tableViewrespondsToSelector:@selector(setSeparatorInset:)]){
[self.tableViewsetSeparatorInset:UIEdgeInsetsZero];
}
if([self.tableViewrespondsToSelector:@selector(setLayoutMargins:)]){
[self.tableViewsetLayoutMargins:UIEdgeInsetsZero];
}
然后在重写willDisplayCell方法
-(void)tableView:(UITableView*)tableViewwillDisplayCell:(UITableViewCell*)cell
forRowAtIndexPath:(NSIndexPath*)indexPath{
if([cellrespondsToSelector:@selector(setSeparatorInset:)]){
[cellsetSeparatorInset:UIEdgeInsetsZero];
}
if([cellrespondsToSelector:@selector(setLayoutMargins:)]){
[cellsetLayoutMargins:UIEdgeInsetsZero];
}
}

6,计算方法耗时时间间隔

//获取时间间隔
#defineTICKCFAbsoluteTimestart=CFAbsoluteTimeGetCurrent();
#defineTOCKNSLog(@"Time:%f",CFAbsoluteTimeGetCurrent()-start)

7,Color颜色宏定义

//随机颜色
#defineRANDOM_COLOR[UIColorcolorWithRed:arc4random_uniform(256)/255.0green:arc4random_uniform(256)/255.0blue:arc4random_uniform(256)/255.0alpha:1]
//颜色(RGB)
#defineRGBCOLOR(r,g,b)[UIColorcolorWithRed:(r)/255.0fgreen:(g)/255.0fblue:(b)/255.0falpha:1]
//利用这种方法设置颜色和透明值,可不影响子视图背景色
#defineRGBACOLOR(r,g,b,a)[UIColorcolorWithRed:(r)/255.0fgreen:(g)/255.0fblue:(b)/255.0falpha:(a)]

8,Alert提示宏定义

#defineAlert(_S_,...)[[[UIAlertViewalloc]initWithTitle:@"提示"message:[NSStringstringWithFormat:(_S_),##__VA_ARGS__]delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil]show]

8,让iOS应用直接退出

-(void)exitApplication{
AppDelegate*app=[UIApplicationsharedApplication].delegate;
UIWindow*window=app.window;

[UIViewanimateWithDuration:1.0fanimations:^{
window.alpha=0;
}completion:^(BOOLfinished){
exit(0);
}];
}

8,NSArray快速求总和最大值最小值和平均值

NSArray*array=[NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil];
CGFloatsum=[[arrayvalueForKeyPath:@"@sum.floatValue"]floatValue];
CGFloatavg=[[arrayvalueForKeyPath:@"@avg.floatValue"]floatValue];
CGFloatmax=[[arrayvalueForKeyPath:@"@max.floatValue"]floatValue];
CGFloatmin=[[arrayvalueForKeyPath:@"@min.floatValue"]floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

9,修改Label中不同文字颜色

-(void)touchesEnded:(NSSet<UITouch*>*)toucheswithEvent:(UIEvent*)event
{
[selfeditStringColor:self.label.texteditStr:@"好"color:[UIColorblueColor]];
}

-(void)editStringColor:(NSString*)stringeditStr:(NSString*)editStrcolor:(UIColor*)color{
//string为整体字符串,editStr为需要修改的字符串
NSRangerange=[stringrangeOfString:editStr];

NSMutableAttributedString*attribute=[[NSMutableAttributedStringalloc]initWithString:string];

//设置属性修改字体颜色UIColor与大小UIFont
[attributeaddAttributes:@{NSForegroundColorAttributeName:color}range:range];

self.label.attributedText=attribute;
}

10,播放声音

#import<AVFoundation/AVFoundation.h>
//1.获取音效资源的路径
NSString*path=[[NSBundlemainBundle]pathForResource:@"pour_milk"ofType:@"wav"];
//2.将路劲转化为url
NSURL*tempUrl=[NSURLfileURLWithPath:path];
//3.用转化成的url创建一个播放器
NSError*error=nil;
AVAudioPlayer*play=[[AVAudioPlayeralloc]initWithContentsOfURL:tempUrlerror:&error];
self.player=play;
//4.播放
[playplay];

11,检测是否IPadPro和其它设备型号

-(BOOL)isIpadPro
{
UIScreen*Screen=[UIScreenmainScreen];
CGFloatwidth=Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloatheight=Screen.nativeBounds.size.height/Screen.nativeScale;
BOOLisIpad=[[UIDevicecurrentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad;
BOOLhasIPadProWidth=fabs(width-1024.f)<DBL_EPSILON;
BOOLhasIPadProHeight=fabs(height-1366.f)<DBL_EPSILON;
returnisIpad&&hasIPadProHeight&&hasIPadProWidth;
}

#defineUI_IS_LANDSCAPE([UIDevicecurrentDevice].orientation==UIDeviceOrientationLandscapeLeft||[UIDevicecurrentDevice].orientation==UIDeviceOrientationLandscapeRight)#defineUI_IS_IPAD([[UIDevicecurrentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad)#defineUI_IS_IPHONE([[UIDevicecurrentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)#defineUI_IS_IPHONE4(UI_IS_IPHONE&&[[UIScreenmainScreen]bounds].size.height<568.0)#defineUI_IS_IPHONE5(UI_IS_IPHONE&&[[UIScreenmainScreen]bounds].size.height==568.0)#defineUI_IS_IPHONE6(UI_IS_IPHONE&&[[UIScreenmainScreen]bounds].size.height==667.0)#defineUI_IS_IPHONE6PLUS(UI_IS_IPHONE&&[[UIScreenmainScreen]bounds].size.height==736.0||[[UIScreenmainScreen]bounds].size.width==736.0)//Bothorientations#defineUI_IS_IOS8_AND_HIGHER([[UIDevicecurrentDevice].systemVersionfloatValue]>=8.0)

文/Originalee(简书作者)原文链接:http://www.jianshu.com/p/9d36aa12429f著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

11,修改TabbarItem的属性

//修改标题位置
self.tabBarItem.titlePositionAdjustment=UIOffsetMake(0,-10);
//修改图片位置
self.tabBarItem.imageInsets=UIEdgeInsetsMake(-3,0,3,0);

//批量修改属性
for(UIBarItem*iteminself.tabBarController.tabBar.items){
[itemsetTitleTextAttributes:[NSDictionarydictionaryWithObjectsAndKeys:
[UIFontfontWithName:@"Helvetica"size:19.0],NSFontAttributeName,nil]
forState:UIControlStateNormal];
}

//设置选中和未选中字体颜色
[[UITabBarappearance]setShadowImage:[[UIImagealloc]init]];

//未选中字体颜色
[[UITabBarItemappearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColorgreenColor]}forState:UIControlStateNormal];

//选中字体颜色
[[UITabBarItemappearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColorcyanColor]}forState:UIControlStateSelected];

12,NULL-nil-Nil-NSNULL的区别

*nil是OC的,空对象,地址指向空(0)的对象。对象的字面零值

*Nil是Objective-C类的字面零值

*NULL是C的,空地址,地址的数值是0,是个长整数

*NSNull用于解决向NSArray和NSDictionary等集合中添加空值的问题

11,去掉BackBarButtonItem的文字

[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0,-60)
forBarMetrics:UIBarMetricsDefault];

12,控件不能交互的一些原因

1,控件的userInteractionEnabled=NO
2,透明度小于等于0.01,aplpha
3,控件被隐藏的时候,hidden=YES
4,子视图的位置超出了父视图的有效范围,子视图无法交互,设置了。
5,需要交互的视图,被其他视图盖住(其他视图开启了用户交互)。

12,修改UITextField中Placeholder的文字颜色

[textsetValue:[UIColorredColor]forKeyPath:@"_placeholderLabel.textColor"];
}

13,视图的生命周期

1、alloc创建对象,分配空间
2、init(initWithNibName)初始化对象,初始化数据
3、loadView从nib载入视图,除非你没有使用xib文件创建视图
4、viewDidLoad载入完成,可以进行自定义数据以及动态创建其他控件
5、viewWillAppear视图将出现在屏幕之前,马上这个视图就会被展现在屏幕上了
6、viewDidAppear视图已在屏幕上渲染完成

1、viewWillDisappear视图将被从屏幕上移除之前执行
2、viewDidDisappear视图已经被从屏幕上移除,用户看不到这个视图了
3、dealloc视图被销毁,此处需要对你在init和viewDidLoad中创建的对象进行释放.

viewVillUnload-当内存过低,即将释放时调用;
viewDidUnload-当内存过低,释放一些不需要的视图时调用。

14,应用程序的生命周期

1,启动但还没进入状态保存:
-(BOOL)application:(UIApplication*)applicationwillFinishLaunchingWithOptions:(NSDictionary*)launchOptions

2,基本完成程序准备开始运行:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions

3,当应用程序将要入非活动状态执行,应用程序不接收消息或事件,比如来电话了:
-(void)applicationWillResignActive:(UIApplication*)application

4,当应用程序入活动状态执行,这个刚好跟上面那个方法相反:
-(void)applicationDidBecomeActive:(UIApplication*)application

5,当程序被推送到后台的时候调用。所以要设置后台继续运行,则在这个函数里面设置即可:
-(void)applicationDidEnterBackground:(UIApplication*)application

6,当程序从后台将要重新回到前台时候调用,这个刚好跟上面的那个方法相反:
-(void)applicationWillEnterForeground:(UIApplication*)application

7,当程序将要退出是被调用,通常是用来保存数据和一些退出前的清理工作:
-(void)applicationWillTerminate:(UIApplication*)application

15,判断view是不是指定视图的子视图

BOOLisView=[textViewisDescendantOfView:self.view];

16,判断对象是否遵循了某协议

if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)]){
[self.selectedControllerperformSelector:@selector(onTriggerRefresh)];
}

17,页面强制横屏

#pragmamark-强制横屏代码
-(BOOL)shouldAutorotate{
//是否支持转屏
returnNO;
}
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
//支持哪些转屏方向
returnUIInterfaceOrientationMaskLandscape;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
returnUIInterfaceOrientationLandscapeRight;
}
-(BOOL)prefersStatusBarHidden{
returnNO;
}

18,系统键盘通知消息

1、UIKeyboardWillShowNotification-将要弹出键盘
2、UIKeyboardDidShowNotification-显示键盘
3、UIKeyboardWillHideNotification-将要隐藏键盘
4、UIKeyboardDidHideNotification-键盘已经隐藏
5、UIKeyboardWillChangeFrameNotification-键盘将要改变frame
6、UIKeyboardDidChangeFrameNotification-键盘已经改变frame

19,关闭navigationController的滑动返回手势

self.navigationController.interactivePopGestureRecognizer.enabled=NO;

20,设置状态栏背景为任意的颜色

-(void)setStatusColor
{
UIView*statusBarView=[[UIViewalloc]initWithFrame:CGRectMake(0,0,[UIScreenmainScreen].bounds.size.width,20)];
statusBarView.backgroundColor=[UIColororangeColor];
[self.viewaddSubview:statusBarView];
}

21,让Xcode的控制台支持LLDB类型的打印

打开终端输入三条命令:
touch~/.lldbinit
echodisplay@importUIKit>>~/.lldbinit
echotargetstop-hookadd-o\"targetstop-hookdisable\">>~/.lldbinit

下次重新运行项目,然后就不报错了。



22,Label行间距

-(void)test{
NSMutableAttributedString*attributedString=
[[NSMutableAttributedStringalloc]initWithString:self.contentLabel.text];
NSMutableParagraphStyle*paragraphStyle=[[NSMutableParagraphStylealloc]init];
[paragraphStylesetLineSpacing:3];

//调整行间距
[attributedStringaddAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0,[self.contentLabel.textlength])];
self.contentLabel.attributedText=attributedString;
}

23,UIImageView填充模式

@"UIViewContentModeScaleToFill",//拉伸自适应填满整个视图
@"UIViewContentModeScaleAspectFit",//自适应比例大小显示
@"UIViewContentModeScaleAspectFill",//原始大小显示
@"UIViewContentModeRedraw",//尺寸改变时重绘
@"UIViewContentModeCenter",//中间
@"UIViewContentModeTop",//顶部
@"UIViewContentModeBottom",//底部
@"UIViewContentModeLeft",//中间贴左
@"UIViewContentModeRight",//中间贴右
@"UIViewContentModeTopLeft",//贴左上
@"UIViewContentModeTopRight",//贴右上
@"UIViewContentModeBottomLeft",//贴左下
@"UIViewContentModeBottomRight",//贴右下

24,宏定义检测block是否可用

#defineBLOCK_EXEC(block,...)if(block){block(__VA_ARGS__);};
//宏定义之前的用法
if(completionBlock){
completionBlock(arg1,arg2);
}
//宏定义之后的用法
BLOCK_EXEC(completionBlock,arg1,arg2);

25,Debug栏打印时自动把Unicode编码转化成汉字

//有时候我们在xcode中打印中文,会打印出Unicode编码,还需要自己去一些在线网站转换,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin插件

26,设置状态栏文字样式颜色

[[UIApplicationsharedApplication]setStatusBarHidden:NO];
[[UIApplicationsharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];

26,自动生成模型代码的插件

//可自动生成模型的代码,省去写模型代码的时间
ESJsonFormat-for-Xcode

27,iOS中的一些手势

轻击手势(TapGestureRecognizer)
轻扫手势(SwipeGestureRecognizer)
长按手势(LongPressGestureRecognizer)
拖动手势(PanGestureRecognizer)
捏合手势(PinchGestureRecognizer)
旋转手势(RotationGestureRecognizer)

27,iOS开发中一些相关的路径

模拟器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs

文档安装位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

插件保存路径:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins

自定义代码段的保存路径:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夹,可以自己新建一个CodeSnippets文件夹。

证书路径
~/Library/MobileDevice/ProvisioningProfiles

28,获取iOS路径的方法

获取家目录路径的函数
NSString*homeDir=NSHomeDirectory();

获取Documents目录路径的方法
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*docDir=[pathsobjectAtIndex:0];

获取Documents目录路径的方法
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString*cachesDir=[pathsobjectAtIndex:0];

获取tmp目录路径的方法:
NSString*tmpDir=NSTemporaryDirectory();

29,字符串相关操作

去除所有的空格
[strstringByReplacingOccurrencesOfString:@""withString:@""]

去除首尾的空格
[strstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];

-(NSString*)uppercaseString;全部字符转为大写字母
-(NSString*)lowercaseString全部字符转为小写字母

30,CocoaPodspodinstall/podupdate更新慢的问题

podinstall--verbose--no-repo-update
podupdate--verbose--no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。

31,MRC和ARC混编设置方式

在XCode中targets的buildphases选项下CompileSources下选择不需要arc编译的文件
双击输入-fno-objc-arc即可

MRC工程中也可以使用ARC的类,方法如下:
在XCode中targets的buildphases选项下CompileSources下选择要使用arc编译的文件
双击输入-fobjc-arc即可

32,把tableview里cell的小对勾的颜色改成别的颜色

_mTableView.tintColor=[UIColorredColor];

33,调整tableview的separaLine线的位置

tableView.separatorInset=UIEdgeInsetsMake(0,100,0,0);

34,设置滑动的时候隐藏navigationbar

navigationController.hidesBarsOnSwipe=Yes

35,自动处理键盘事件,实现输入框防遮挡的插件

IQKeyboardManager'target='_blank'>https://github.com/hackiftekhar/IQKeyboardManager[/code]36,Quartz2D相关

图形上下是一个CGContextRef类型的数据。
图形上下文包含:
1,绘图路径(各种各样图形)
2,绘图状态(颜色,线宽,样式,旋转,缩放,平移)
3,输出目标(绘制到什么地方去?UIView、图片)

1,获取当前图形上下文
CGContextRefctx=UIGraphicsGetCurrentContext();
2,添加线条
CGContextMoveToPoint(ctx,20,20);
3,渲染
CGContextStrokePath(ctx);
CGContextFillPath(ctx);
4,关闭路径
CGContextClosePath(ctx);
5,画矩形
CGContextAddRect(ctx,CGRectMake(20,20,100,120));
6,设置线条颜色
[[UIColorredColor]setStroke];
7,设置线条宽度
CGContextSetLineWidth(ctx,20);
8,设置头尾样式
CGContextSetLineCap(ctx,kCGLineCapSquare);
9,设置转折点样式
CGContextSetLineJoin(ctx,kCGLineJoinBevel);
10,画圆
CGContextAddEllipseInRect(ctx,CGRectMake(30,50,100,100));
11,指定圆心
CGContextAddArc(ctx,100,100,50,0,M_PI*2,1);
12,获取图片上下文
UIGraphicsGetImageFromCurrentImageContext();
13,保存图形上下文
CGContextSaveGState(ctx)
14,恢复图形上下文
CGContextRestoreGState(ctx)

37,屏幕截图

//1.开启一个与图片相关的图形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

//2.获取当前图形上下文
CGContextRefctx=UIGraphicsGetCurrentContext();

//3.获取需要截取的view的layer
[self.view.layerrenderInContext:ctx];

//4.从当前上下文中获取图片
UIImage*image=UIGraphicsGetImageFromCurrentImageContext();

//5.关闭图形上下文
UIGraphicsEndImageContext();

//6.把图片保存到相册
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);

37,左右抖动动画

//1,创建核心动画
CAKeyframeAnimation*keyAnima=[CAKeyframeAnimationanimation];

//2,告诉系统执行什么动画。
keyAnima.keyPath=@"transform.rotation";
keyAnima.values=@[@(-M_PI_4/90.0*5),@(M_PI_4/90.0*5),@(-M_PI_4/90.0*5)];

//3,执行完之后不删除动画
keyAnima.removedOnCompletion=NO;

//4,执行完之后保存最新的状态
keyAnima.fillMode=kCAFillModeForwards;

//5,动画执行时间
keyAnima.duration=0.2;

//6,设置重复次数。
keyAnima.repeatCount=MAXFLOAT;

//7,添加核心动画
[self.iconView.layeraddAnimation:keyAnimaforKey:nil];

38,CALayer的知识

CALayer负责视图中显示内容和动画
UIView负责监听和响应事件

创建UIView对象时,UIView内部会自动创建一个图层(既CALayer)
UIView本身不具备显示的功能,是它内部的层才有显示功能.

CALayer属性:
position中点(由anchorPoint决定)
anchorPoint锚点
borderColor边框颜色
borderWidth边框宽度
cornerRadius圆角半径
shadowColor阴影颜色
contents内容
opacity透明度
shadowOpacity偏移
shadowRadius阴影半径
shadowColor阴影颜色
masksToBounds裁剪

39,性能相关

1.视图复用,比如UITableViewCell,UICollectionViewCell.
2.数据缓存,比如用SDWebImage实现图片缓存。
3.任何情况下都不能堵塞主线程,把耗时操作尽量放到子线程。
4.如果有多个下载同时并发,可以控制并发数。
5.在合适的地方尽量使用懒加载。
6.重用重大开销对象,比如:NSDateFormatter、NSCalendar。
7.选择合适的数据存储。
8.避免循环引用。避免delegate用retain、strong修饰,block可能导致循环引用,NSTimer也可能导致内存泄露等。
9.当涉及到定位的时候,不用的时候最好把定位服务关闭。因为定位耗电、流量。
10.加锁对性能有重大开销。
11.界面最好不要添加过多的subViews.
12.TableView如果不同行高,那么返回行高,最好做缓存。
13.Viewdidload里尽量不要做耗时操作。

40,验证身份证号码

//验证身份证号码
-(BOOL)checkIdentityCardNo:(NSString*)cardNo
{
if(cardNo.length!=18){
returnNO;
}
NSArray*codeArray=[NSArrayarrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2",nil];
NSDictionary*checkCodeDic=[NSDictionarydictionaryWithObjects:[NSArrayarrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2",nil]forKeys:[NSArrayarrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",nil]];

NSScanner*scan=[NSScannerscannerWithString:[cardNosubstringToIndex:17]];

intval;
BOOLisNum=[scanscanInt:&val]&&[scanisAtEnd];
if(!isNum){
returnNO;
}
intsumValue=0;

for(inti=0;i<17;i++){
sumValue+=[[cardNosubstringWithRange:NSMakeRange(i,1)]intValue]*[[codeArrayobjectAtIndex:i]intValue];
}

NSString*strlast=[checkCodeDicobjectForKey:[NSStringstringWithFormat:@"%d",sumValue%11]];

if([strlastisEqualToString:[[cardNosubstringWithRange:NSMakeRange(17,1)]uppercaseString]]){
returnYES;
}
returnNO;
}

41,响应者链条顺序

1>当应用程序启动以后创建UIApplication对象

2>然后启动“消息循环”监听所有的事件

3>当用户触摸屏幕的时候,"消息循环"监听到这个触摸事件

4>"消息循环"首先把监听到的触摸事件传递了UIApplication对象

5>UIApplication对象再传递给UIWindow对象

6>UIWindow对象再传递给UIWindow的根控制器(rootViewController)

7>控制器再传递给控制器所管理的view

8>控制器所管理的View在其内部搜索看本次触摸的点在哪个控件的范围内(调用Hittest检测是否在这个范围内)

9>找到某个控件以后(调用这个控件的touchesXxx方法),再一次向上返回,最终返回给"消息循环"

10>"消息循环"知道哪个按钮被点击后,在搜索这个按钮是否注册了对应的事件,如果注册了,那么就调用这个"事件处理"程序。(一般就是执行控制器中的"事件处理"方法)

42,使用函数式指针执行方法和忽略performSelector方法的时候警告

不带参数的:
SELselector=NSSelectorFromString(@"someMethod");
IMPimp=[_controllermethodForSelector:selector];
void(*func)(id,SEL)=(void*)imp;
func(_controller,selector);

带参数的:
SELselector=NSSelectorFromString(@"processRegion:ofView:");
IMPimp=[_controllermethodForSelector:selector];
CGRect(*func)(id,SEL,CGRect,UIView*)=(void*)imp;
CGRectresult=func(_controller,selector,someRect,someView);

忽略警告:
#pragmaclangdiagnosticpush
#pragmaclangdiagnosticignored"-Warc-performSelector-leaks"
[someControllerperformSelector:NSSelectorFromString(@"someMethod")]
#pragmaclangdiagnosticpop

如果需要忽视的警告有多处,可以定义一个宏:
#defineSuppressPerformSelectorLeakWarning(Stuff)\
do{\
_Pragma("clangdiagnosticpush")\
_Pragma("clangdiagnosticignored\"-Warc-performSelector-leaks\"")\
Stuff;\
_Pragma("clangdiagnosticpop")\
}while(0)
使用方法:
SuppressPerformSelectorLeakWarning(
[_targetperformSelector:_actionwithObject:self]
);

43,UIApplication的简单使用

--------设置角标数字--------
//获取UIApplication对象
UIApplication*ap=[UIApplicationsharedApplication];
//在设置之前,要注册一个通知,从ios8之后,都要先注册一个通知对象.才能够接收到提醒.
UIUserNotificationSettings*notice=
[UIUserNotificationSettingssettingsForTypes:UIUserNotificationTypeBadgecategories:nil];
//注册通知对象
[apregisterUserNotificationSettings:notice];
//设置提醒数字
ap.applicationIconBadgeNumber=20;

--------设置联网状态--------
UIApplication*ap=[UIApplicationsharedApplication];
ap.networkActivityIndicatorVisible=YES;
--------------------------

44,UITableView隐藏空白部分线条

self.tableView.tableFooterView=[[UIViewalloc]init];

45,显示git增量的Xcode插件:GitDiff

下载地址:https://github.com/johnno1962/GitDiff
这款插件的名字是GitDiff,作用就是可以显示表示出git增量提交的代码行,比如下图
会在Xcode左边标识出来:




46,各种收藏的网址

unicode编码转换http://tool.chinaz.com/tools/unicode.aspx
JSON字符串格式化http://www.runoob.com/jsontool
RGB颜色值转换http://www.sioe.cn/yingyong/yanse-rgb-16/
短网址生成http://dwz.wailian.work/
objc中国'target='_blank'>http://objccn.io/[/code]47,NSObject继承图



48,浅拷贝、深拷贝、copy和strong

浅拷贝:(任何一方的变动都会影响到另一方)
只是对对象的简单拷贝,让几个对象共用一片内存,当内存销毁的时候,指向这片内存的几个指针
需要重新定义才可以使用。

深拷贝:(任何一方的变动都不会影响到另一方)
拷贝对象的具体内容,内存地址是自主分配的,拷贝结束后,两个对象虽然存的值是相同的,但是
内存地址不一样,两个对象也互不影响,互不干涉。

copy和Strong的区别:copy是创建一个新对象,Strong是创建一个指针。

49,SEL和IMP

SEL:其实是对方法的一种包装,将方法包装成一个SEL类型的数据,去寻找对应的方法地址,找到方法地址后
就可以调用方法。这些都是运行时特性,发消息就是发送SEL,然后根据SEL找到地址,调用方法。

IMP:是”implementation”的缩写,它是objetive-C方法(method)实现代码块的地址,类似函数
指针,通过它可以直接访问任意一个方法。免去发送消息的代价。

50,self和super

在动态方法中,self代表着"对象"
在静态方法中,self代表着"类"

万变不离其宗,记住一句话就行了:
self代表着当前方法的调用者self和super是oc提供的两个保留字,但有根本区别,self是类的隐藏的
参数变量,指向当前调用方法的对象(类也是对象,类对象)
另一个隐藏参数是_cmd,代表当前类方法的selector。

super并不是隐藏的参数,它只是一个"编译器指示符"
super就是个障眼法发,编译器符号,它可以替换成[selfclass],只不过方法是从self的
超类开始寻找。

51,长连接和短连接

长连接:(长连接在没有数据通信时,定时发送数据包(心跳),以维持连接状态)
连接→数据传输→保持连接(心跳)→数据传输→保持连接(心跳)→……→关闭连接;
长连接:连接服务器就不断开

短连接:(短连接在没有数据传输时直接关闭就行了)
连接→数据传输→关闭连接;
短连接:连接上服务器,获取完数据,就立即断开。

52,HTTP基本状态码

200OK
请求已成功,请求所希望的响应头或数据体将随此响应返回。

300MultipleChoices
被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。

400BadRequest
由于包含语法错误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求。

404NotFound
请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下。

408RequestTimeout
请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改。

500InternalServerError
服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现。

53,TCP和UDP

TCP:

-建立连接,形成传输数据的通道
-在连接中进行大数据传输(数据大小受限制)
-通过三次握手完成连接,是可靠协议
-必须建立连接,效率比UDP低

UDP:

-只管发送,不管接受
-将数据以及源和目的封装成数据包中,不需要建立连接、
-每个数据报的大小限制在64K之内
-不可靠协议
-速度快

54,三次握手和四次断开

三次握手:
你在吗-我在的-我问你个事情
四次断开握手
我这个问题问完了--你问完了吗---可以下线了吗---我真的问完了拜拜

55,设置按钮按下时候会发光

button.showsTouchWhenHighlighted=YES;

56,怎么把tableview里Cell的小对勾颜色改成别的颜色?

_mTableView.tintColor=[UIColorredColor];

57,怎么调整Cell的separaLine的位置?**

_myTableView.separatorInset=UIEdgeInsetsMake(0,100,0,0);

58,ScrollView莫名其妙不能在viewController划到顶怎么办?

self.automaticallyAdjustsScrollViewInsets=NO;

59,设置TableView不显示没内容的Cell。

self.tableView.tableFooterView=[[UIViewalloc]init]

60,复制字符串到iOS剪贴板

UIPasteboard*pasteboard=[UIPasteboardgeneralPasteboard];
pasteboard.string=self.label.text;

61,宏定义多行使用方法

例子:(只需要每行加个\就行了)

#defineYKCodingScanData\
-(void)setValue:(id)valueforUndefinedKey:(NSString*)key{}\
-(instancetype)initWithScanJson:(NSDictionary*)dict{\
if(self=[superinit]){\
[selfsetValuesForKeysWithDictionary:dict];\
}\
returnself;\
}\

62,去掉cell点击后背景变色

[tableViewdeselectRowAtIndexPath:indexPathanimated:NO];
如果发现在tableView的didSelect中present控制器弹出有些慢也可以试试这个方法

63,线程租调度事例

//群组-统一监控一组任务
dispatch_group_tgroup=dispatch_group_create();

dispatch_queue_tq=dispatch_get_global_queue(0,0);
//添加任务
//group负责监控任务,queue负责调度任务
dispatch_group_async(group,q,^{
[NSThreadsleepForTimeInterval:1.0];
NSLog(@"任务1%@",[NSThreadcurrentThread]);
});
dispatch_group_async(group,q,^{
NSLog(@"任务2%@",[NSThreadcurrentThread]);
});
dispatch_group_async(group,q,^{
NSLog(@"任务3%@",[NSThreadcurrentThread]);
});

//监听所有任务完成-等到group中的所有任务执行完毕后,"由队列调度block中的任务异步执行!"
dispatch_group_notify(group,dispatch_get_main_queue(),^{
//修改为主队列,后台批量下载,结束后,主线程统一更新UI
NSLog(@"OK%@",[NSThreadcurrentThread]);
});

NSLog(@"comehere");

64、视图坐标转换

//将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值
-(CGPoint)convertPoint:(CGPoint)pointtoView:(UIView*)view;
//将像素point从view中转换到当前视图中,返回在当前视图中的像素值
-(CGPoint)convertPoint:(CGPoint)pointfromView:(UIView*)view;

//将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect
-(CGRect)convertRect:(CGRect)recttoView:(UIView*)view;
//将rect从view中转换到当前视图中,返回在当前视图中的rect
-(CGRect)convertRect:(CGRect)rectfromView:(UIView*)view;

*例把UITableViewCell中的subview(btn)的frame转换到
controllerA中
//controllerA中有一个UITableView,UITableView里有多行UITableVieCell,cell上放有一个button
//在controllerA中实现:
CGRectrc=[cellconvertRect:cell.btn.frametoView:self.view];
或
CGRectrc=[self.viewconvertRect:cell.btn.framefromView:cell];
//此rc为btn在controllerA中的rect

或当已知btn时:
CGRectrc=[btn.superviewconvertRect:btn.frametoView:self.view];
或
CGRectrc=[self.viewconvertRect:btn.framefromView:btn.superview];

65、设置animation动画终了,不返回初始状态

animation.removedOnCompletion=NO;
animation.fillMode=kCAFillModeForwards;

66、UIViewAnimationOptions类型

常规动画属性设置(可以同时选择多个进行设置)
UIViewAnimationOptionLayoutSubviews:动画过程中保证子视图跟随运动。
UIViewAnimationOptionAllowUserInteraction:动画过程中允许用户交互。
UIViewAnimationOptionBeginFromCurrentState:所有视图从当前状态开始运行。
UIViewAnimationOptionRepeat:重复运行动画。
UIViewAnimationOptionAutoreverse:动画运行到结束点后仍然以动画方式回到初始点。
UIViewAnimationOptionOverrideInheritedDuration:忽略嵌套动画时间设置。
UIViewAnimationOptionOverrideInheritedCurve:忽略嵌套动画速度设置。
UIViewAnimationOptionAllowAnimatedContent:动画过程中重绘视图(注意仅仅适用于转场动画)。
UIViewAnimationOptionShowHideTransitionViews:视图切换时直接隐藏旧视图、显示新视图,而不是将旧视图从父视图移除(仅仅适用于转场动画)UIViewAnimationOptionOverrideInheritedOptions:不继承父动画设置或动画类型。
2.动画速度控制(可从其中选择一个设置)
UIViewAnimationOptionCurveEaseInOut:动画先缓慢,然后逐渐加速。
UIViewAnimationOptionCurveEaseIn:动画逐渐变慢。
UIViewAnimationOptionCurveEaseOut:动画逐渐加速。
UIViewAnimationOptionCurveLinear:动画匀速执行,默认值。
3.转场类型(仅适用于转场动画设置,可以从中选择一个进行设置,基本动画、关键帧动画不需要设置)
UIViewAnimationOptionTransitionNone:没有转场动画效果。
UIViewAnimationOptionTransitionFlipFromLeft:从左侧翻转效果。
UIViewAnimationOptionTransitionFlipFromRight:从右侧翻转效果。
UIViewAnimationOptionTransitionCurlUp:向后翻页的动画过渡效果。
UIViewAnimationOptionTransitionCurlDown:向前翻页的动画过渡效果。
UIViewAnimationOptionTransitionCrossDissolve:旧视图溶解消失显示下一个新视图的效果。
UIViewAnimationOptionTransitionFlipFromTop:从上方翻转效果。
UIViewAnimationOptionTransitionFlipFromBottom:从底部翻转效果。

1.颜色转变成图片

-(UIImage*)createImageWithColor:(UIColor*)color
{
CGRectrect=CGRectMake(0.0f,0.0f,1.0f,1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRefcontext=UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,[colorCGColor]);
CGContextFillRect(context,rect);
UIImage*theImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returntheImage;
}

2.app评分跳转

-(void)goToAppStore
{
NSString*str=[NSStringstringWithFormat:
@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d",547203890];
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:str]];
}

3.获取当前系统语言环境

NSUserDefaults*defs=[NSUserDefaultsstandardUserDefaults];
NSArray*languages=[defsobjectForKey:@"AppleLanguages"];
NSString*preferredLang=[languagesobjectAtIndex:0];

4.计算字符串的高度

NSString*str=@"chuanzhang";
NSMutableParagraphStyle*paragraphStyle=[[NSMutableParagraphStylealloc]init];
paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
NSDictionary*dicAtt=[NSDictionarydictionaryWithObjectsAndKeys:[UIFontsystemFontOfSize:15],NSFontAttributeName,paragraphStyle.copy,NSParagraphStyleAttributeName,nil];
NSAttributedString*attribute=[[NSAttributedStringalloc]initWithString:strattributes:dicAtt];
CGRectframe=[attributeboundingRectWithSize:CGSizeMake(200,MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigincontext:nil];

5.强行关闭app的方法

//私有API
[[UIApplicationsharedApplication]performSelector:@selector(terminateWithSuccess)];
//C语言方法
exit(0);

6.如何快速的查看一段代码的执行时间

#defineTICKNSDate*startTime=[NSDatedate]
#defineTOCKNSLog(@"Time:%f",-[startTimetimeIntervalSinceNow])
//在想要查看执行时间的代码的地方进行这么处理
TICK
//doyourworkhere
TOCK

7.在使用view的缩放的时候,layer.border.width随着view的放大,会出现锯齿化的问题,解决这个问题需要设置这个属性。

self.layer.allowsEdgeAntialiasing=YES;

8.instrument中timeprofile中的self,#self,%self各代表什么?



333.jpeg

下面引用了一下网上的具体内容


Selfis"Thenumberoftimesthesymbolcallsitself."accordingtotheAppleDocsontheTimeProfiler.

Fromthewaythenumberslookthough,itseemsselfisthesummeddurationofsamplesthathadthissymbolatthebottomofitsstacktrace.Thatwouldmake:

self:thenumberofsampleswherethissymbolwasatthebottomofthestacktrace

%self:thepercentofselfsamplesrelativetototalsamplesofcurrentlydisplayedcalltree

(eg-#self/totalsamples).
Sothiswouldn'ttellyouhowmanytimesamethodwascalled.Butitwouldgiveyouanideahowmuchtimeisspentinamethodorlowerinthecalltree.


9.神器计算图片位置的函数:
AVMakeRectWithAspectRatioInsideRect()

通过这个函数,我们可以计算一个图片放在另一个view按照一定的比例居中显示,可能说的我比较抽象,还是用图来显示,可以说它可以直接一个image以任何的比例显示显示在imageview中居中所处的位置,拿UIViewContontAspectFit来演示

UIImageView*imageView=[[UIImageViewalloc]initWithFrame:CGRectMake(100,100,300,300)];
imageView.center=self.view.center;
imageView.backgroundColor=[UIColorredColor];
imageView.contentMode=UIViewContentModeScaleAspectFit;
UIImage*image=[UIImageimageNamed:@"mm.jpg"];
imageView.image=image;

CGRectiamgeAspectRect=AVMakeRectWithAspectRatioInsideRect(image.size,imageView.bounds);
NSLog(@"iamgeAspectRect=%@,imageView=%@",NSStringFromCGRect(iamgeAspectRect),NSStringFromCGRect(imageView.frame));
[self.viewaddSubview:imageView];


mm.pn

log打因结果如下:

iamgeAspectRect={{37.563884156729145,0},{224.87223168654171,300}},imageView={{37.5,183.5},{300,300}}

可以从log得出对应的image以aspectFit的方式在imageView的位置,在imageView中的位置是(37.5,0)。这样你根本不需要任何多的代码来计算了。(ps:这个函数是在AV框架的,童鞋们自行导入。)

具体它的其他的好处,如果你是做相机或者图片处理的你就知道它的好处了,什么处理横屏照片了,16:9,1:1,4:3图片在控件中的位置,控件上的点对应图片上的点的位置拉,等等。

10.关于如果一个矩形如果做了平移旋转缩放等一系列操作之后,上下左右的四个点(甚至矩形上任意一个点)的位置。

CGPointoriginalCenter=CGPointApplyAffineTransform(_mStyleLeftEyeView.center,
CGAffineTransformInvert(_mStyleLeftEyeView.transform));

//1左眼内眼角
CGPointbottomRight=originalCenter;
bottomRight.x+=_mStyleLeftEyeView.bounds.size.width/2;
bottomRight.y+=_mStyleLeftEyeView.bounds.size.height/2;
bottomRight=CGPointApplyAffineTransform(bottomRight,_mStyleLeftEyeView.transform);

首先这个styleLeftView就是一个矩形的view,这里以右下角的点做示范,做无论做了任何的tranform之后都可以得到它的点的位置
11.tableViewCell上的button,点击获取所在row

UITableViewCell*cell=(UITableViewCell*)[[btnsuperview]superview];
NSIndexPath*indexPath=[self.tableViewindexPathForCell:cell];

12.设置粘贴内容

[UIPasteboardgeneralPasteboard].string=@"string";
//获取粘贴内容
NSString*string=[UIPasteboardgeneralPasteboard].string;

13.iPhone为了节省电力所以有一个自动休眠机制,如果想让我们的APP不自动进入休眠只需要设置UIApplication的idleTimerDisabled属性为YES即可。(切勿滥用)
示例:

[UIApplicationsharedApplication].idleTimerDisabled=YES;

14.
UIApplicationUserDidTakeScreenshotNotification
通知,当用户截屏时触发

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(screenCapture)name:UIApplicationUserDidTakeScreenshotNotificationobject:nil];
-(void)screenCapture{
//doSomething
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
章节导航