收藏 - iOS开发小技巧总结

打印 View 所有子视图
po [[self view]recursiveDescription]
layoutSubviews 调用的调用时机
当视图第一次显示的时候会被调用
当这个视图显示到屏幕上了, 点击按钮
添加子视图也会调用这个方法
当本视图的大小发生改变的时候是会调用的
当子视图的 frame 发生改变的时候是会调用的
当删除子视图的时候是会调用的
NSString 过滤特殊字符
// 定义一个特殊字符的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-*+=_\|~<>$€^•'@#$%^&*()_+'""];
// 过滤字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
TransForm 属性
// 平移按钮
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);

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

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

// 初始化复位
self.buttonView.transform = CGAffineTransformIdentity;
去掉分割线多余 15 像素

首先在 viewDidLoad 方法加入以下代码:

if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
       [self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
       [self.tableView setLayoutMargins:UIEdgeInsetsZero];
}

然后在重写 willDisplayCell 方法

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
             [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
             [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
计算方法耗时时间间隔
// 获取时间间隔
#define TICK   CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define TOCK   NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

TICK;
// 你的运行事件
TOCK;

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)]
Alert 提示宏定义
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show]
让 iOS 应用直接退出
- (void)exitApplication {
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;

    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
    } completion:^(BOOL finished) {
        exit(0);
    }];
}
NSArray 快速求总和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
修改 Label 中不同文字颜色
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}

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

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

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

    self.label.attributedText = attribute;
}
播放声音
#import
 //  1. 获取音效资源的路径
 NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
 //  2. 将路劲转化为 url
 NSURL *tempUrl = [NSURL fileURLWithPath:path];
 //  3. 用转化成的 url 创建一个播放器
 NSError *error = nil;
 AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
 self.player = play;
 //  4. 播放
 [play play];
检测是否 IPad Pro 和其它设备型号
- (BOOL)isIpadPro
{
  UIScreen *Screen = [UIScreen mainScreen];
  CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;
  CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;
  BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
  BOOL hasIPadProWidth = fabs(width - 1024.f) = 8.0)
修改 Tabbar Item 的属性
// 修改标题位置
 self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
 // 修改图片位置
 self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);

 // 批量修改属性
 for (UIBarItem *item in self.tabBarController.tabBar.items) {
     [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
              [UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
                         forState:UIControlStateNormal];
 }

 // 设置选中和未选中字体颜色
 [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

 // 未选中字体颜色
 [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];

 // 选中字体颜色
 [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];
控件不能交互的一些原因
1,控件的 userInteractionEnabled = NO
2,透明度小于等于 0.01,aplpha
3,控件被隐藏的时候,hidden = YES
4,子视图的位置超出了父视图的有效范围,子视图无法交互,设置了。
5,需要交互的视图,被其他视图盖住(其他视图开启了用户交互)。
修改 UITextField 中 Placeholder 的文字颜色
[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
视图的生命周期
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-当内存过低,释放一些不需要的视图时调用。
应用程序的生命周期

1,启动但还没进入状态保存 :

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions

2,基本完成程序准备开始运行:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(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
判断 view 是不是指定视图的子视图
BOOL isView =  [textView isDescendantOfView:self.view];
判断对象是否遵循了某协议
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) {
    [self.selectedController performSelector:@selector(onTriggerRefresh)];
}
页面强制横屏
#pragma mark - 强制横屏代码
- (BOOL)shouldAutorotate{
    // 是否支持转屏
    return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    // 支持哪些转屏方向
    return UIInterfaceOrientationMaskLandscape;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}
- (BOOL)prefersStatusBarHidden{
    return NO;
}
系统键盘通知消息
1、UIKeyboardWillShowNotification- 将要弹出键盘
2、UIKeyboardDidShowNotification- 显示键盘
3、UIKeyboardWillHideNotification- 将要隐藏键盘
4、UIKeyboardDidHideNotification- 键盘已经隐藏
5、UIKeyboardWillChangeFrameNotification- 键盘将要改变 frame
6、UIKeyboardDidChangeFrameNotification- 键盘已经改变 frame
关闭 navigationController 的滑动返回手势
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
设置状态栏背景为任意的颜色
- (void)setStatusColor
{
    UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    statusBarView.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:statusBarView];
}
让 Xcode 的控制台支持 LLDB 类型的打印

打开终端输入三条命令:

touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o "target stop-hook disable" >> ~/.lldbinit

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

Label 行间距
-(void)test{
    NSMutableAttributedString *attributedString =
   [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
    NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];
   [paragraphStyle setLineSpacing:3];

    // 调整行间距
   [attributedString addAttribute:NSParagraphStyleAttributeName
                         value:paragraphStyle
                         range:NSMakeRange(0, [self.contentLabel.text length])];
     self.contentLabel.attributedText = attributedString;
}
UIImageView 填充模式
@"UIViewContentModeScaleToFill",      // 拉伸自适应填满整个视图
@"UIViewContentModeScaleAspectFit",   // 自适应比例大小显示
@"UIViewContentModeScaleAspectFill",  // 原始大小显示
@"UIViewContentModeRedraw",           // 尺寸改变时重绘
@"UIViewContentModeCenter",           // 中间
@"UIViewContentModeTop",              // 顶部
@"UIViewContentModeBottom",           // 底部
@"UIViewContentModeLeft",             // 中间贴左
@"UIViewContentModeRight",            // 中间贴右
@"UIViewContentModeTopLeft",          // 贴左上
@"UIViewContentModeTopRight",         // 贴右上
@"UIViewContentModeBottomLeft",       // 贴左下
@"UIViewContentModeBottomRight",      // 贴右下
宏定义检测 block 是否可用
#define BLOCK_EXEC(block, ...) if (block) {block(__VA_ARGS__); };
// 宏定义之前的用法
 if (completionBlock)   {
    completionBlock(arg1, arg2);
  }
// 宏定义之后的用法
 BLOCK_EXEC(completionBlock, arg1, arg2);
设置状态栏文字样式颜色

[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];


###### 自动生成模型代码的插件
// 可自动生成模型的代码,省去写模型代码的时间
ESJsonFormat-for-Xcode
iOS 中的一些手势

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


###### 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/Provisioning Profiles
获取 iOS 路径的方法

获取家目录路径的函数

NSString *homeDir = NSHomeDirectory();

获取 Documents 目录路径的方法

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

获取 Documents 目录路径的方法

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

获取 tmp 目录路径的方法:

NSString *tmpDir = NSTemporaryDirectory();
字符串相关操作

去除所有的空格

[str stringByReplacingOccurrencesOfString:@" " withString:@""]

去除首尾的空格

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

- (NSString *)uppercaseString;  全部字符转为大写字母
- (NSString *)lowercaseString  全部字符转为小写字母
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容