iOS 常用小技巧大杂烩(上)

来源:互联网 发布:消防大数据内容 编辑:程序博客网 时间:2024/05/18 00:30



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,计算方法耗时时间间隔


// 获取时间间隔

#define TICK   CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

#define TOCK   NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)


7,Color颜色宏定义


// 随机颜色

#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

// 颜色(RGB)

#define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

// 利用这种方法设置颜色和透明值,可不影响子视图背景色

#define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]


8,Alert提示宏定义


#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"确定" 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(@"%fn%fn%fn%f",sum,avg,max,min);


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


-(void)touchesEnded:(NSSet *)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

  //  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,检测是否IPad Pro和其它设备型号


-(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) = 8.0)


11,修改Tabbar Item的属性


   // 修改标题位置

    self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);

    // 修改图片位置

    self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3,0,3,0);

 

    // 批量修改属性

    for(UIBarItem *item inself.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.01aplpha

3,控件被隐藏的时候,hidden = YES

4,子视图的位置超出了父视图的有效范围,子视图无法交互,设置了。

5,需要交互的视图,被其他视图盖住(其他视图开启了用户交互)。



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


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


13,视图的生命周期


1alloc创建对象,分配空间

2init(initWithNibName)初始化对象,初始化数据

3loadViewnib载入视图,除非你没有使用xib文件创建视图

4viewDidLoad载入完成,可以进行自定义数据以及动态创建其他控件

5viewWillAppear视图将出现在屏幕之前,马上这个视图就会被展现在屏幕上了

6viewDidAppear视图已在屏幕上渲染完成

 

1viewWillDisappear视图将被从屏幕上移除之前执行

2viewDidDisappear视图已经被从屏幕上移除,用户看不到这个视图了

3dealloc视图被销毁,此处需要对你在initviewDidLoad中创建的对象进行释放.

 

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,页面强制横屏


#pragma mark - 强制横屏代码

-(BOOL)shouldAutorotate{    

    //是否支持转屏      

    returnNO;

}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations{    

    //支持哪些转屏方向    

    returnUIInterfaceOrientationMaskLandscape;

}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{              

    returnUIInterfaceOrientationLandscapeRight;

}

-(BOOL)prefersStatusBarHidden{  

    returnNO;

}


18,系统键盘通知消息


1UIKeyboardWillShowNotification-将要弹出键盘

2UIKeyboardDidShowNotification-显示键盘

3UIKeyboardWillHideNotification-将要隐藏键盘

4UIKeyboardDidHideNotification-键盘已经隐藏

5UIKeyboardWillChangeFrameNotification-键盘将要改变frame

6UIKeyboardDidChangeFrameNotification-键盘已经改变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

    echo target stop-hookadd -o"target stop-hook disable" >> ~/.lldbinit


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



22,Label行间距


-voidtest{

    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是否可用


#define BLOCK_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全部字符转为小写字母


0 0
原创粉丝点击