iOS大杂烩-常用小知识

  1. 打印View所有子视图
    po [[self view]recursiveDescription]
  2. layoutSubviews调用的调用时机* 当视图第一次显示的时候会被调用* 当这个视图显示到屏幕上了,点击按钮* 添加子视图也会调用这个方法* 当本视图的大小发生改变的时候是会调用的* 当子视图的frame发生改变的时候是会调用的* 当删除子视图的时候是会调用的
  3. NSString过滤特殊字符
// 定义一个特殊字符的集合
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];// 过滤字符串的特殊字符NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
  1. 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;
  1. 去掉分割线多余15像素首先在viewDidLoad方法加入以下代码:
 if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {        [self.tableView setSeparatorInset:UIEdgeInsetsZero];    } 
   if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {                [self.tableView setLayoutMargins:UIEdgeInsetsZero];}
  1. 计算方法耗时时间间隔
// 获取时间间隔#define TICK  CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();#define TOCK  NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
  1. 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)]
  1. 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 = [UIApplication sharedApplication].delegate;    UIWindow *window = app.window;    [UIView animateWithDuration:1.0f animations:^{        window.alpha = 0;    } completion:^(BOOL finished) {        exit(0);    }];}
  1. 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(@"%f\n%f\n%f\n%f",sum,avg,max,min);

检测是否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) < DBL_EPSILON;

BOOL hasIPadProHeight = fabs(height - 1366.f) < DBL_EPSILON;

return isIpad && hasIPadProHeight && hasIPadProWidth;

}

修改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];

NULL - nil - Nil - NSNULL的区别

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

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

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

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

去掉BackBarButtonItem的文字

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

控件不能交互的一些原因

  • 控件的userInteractionEnabled = NO

  • 透明度小于等于0.01,aplpha

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

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

修改UITextField中Placeholder的文字颜色

[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

视图的生命周期

  • alloc 创建对象,分配空间

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

  • loadView 从nib载入视图 ,除非你没有使用xib文件创建视图

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

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

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

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

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

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

  • viewVillUnload- 当内存过低,即将释放时调用;

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

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

BOOL isView =  [textView isDescendantOfView:self.view];

页面强制横屏

//pragma mark - 强制横屏代码

- (BOOL)shouldAutorotate{

//是否支持转屏

return NO;

}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{

//支持哪些转屏方向

return UIInterfaceOrientationMaskLandscape;

}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{

return UIInterfaceOrientationLandscapeRight;

}

- (BOOL)prefersStatusBarHidden{

return NO;

}

系统键盘通知消息

  • UIKeyboardWillShowNotification-将要弹出键盘

  • UIKeyboardDidShowNotification-显示键盘

  • UIKeyboardWillHideNotification-将要隐藏键盘

  • UIKeyboardDidHideNotification-键盘已经隐藏

  • UIKeyboardWillChangeFrameNotification-键盘将要改变frame

  • 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",      // 贴右下
  • 获取时间
//获取当地时间
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}
//将字符串转成NSDate类型
- (NSDate *)dateFromString:(NSString *)dateString {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}
//传入今天的时间,返回明天的时间
- (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 1. 打印View所有子视图 po [[self view]recursiveDescription] 2. la...
    Hurricane_4283阅读 865评论 0 2
  • 打印View所有子视图 layoutSubviews调用的调用时机 当视图第一次显示的时候会被调用当这个视图显示到...
    hyeeyh阅读 466评论 0 3
  • iOS 常用小技巧大杂烩(上) 2016-06-02 iOS大全 (点击上方公众号,可快速关注) 来源:品味_生活...
    鬣狗赛跑阅读 266评论 0 1
  • 1. 最好的盟友并不是一开头支持我们的人, , 而是那些一开头反对我们, 然后转向支持我们的人 古语常说“化敌为友...
    Brandon_13dd阅读 247评论 0 2
  • 特别说明,为便于查阅,文章转自https://github.com/getify/You-Dont-Know-JS...
    杀破狼real阅读 445评论 0 0