自从6月份的 WWDC大会展示了
iOS 13
的新版本之后,广大开发者朋友又面临着新一轮的系统升级适配工作;随着苹果9月份发布会脚步的临近,对公司的App升级适配势在必行。
iOS 13发现问题回顾
- 禁止用户获取或直接设置私有属性:调用
setValue:forKeyPath:
、valueForKey:
方法会引起App崩溃。例如:UITextField
修改_placeholderLabel.textColor
、UISearchBar
修改_searchField
UITextField
的leftView
和rightView
调整:部分视图位置显示异常UITabBar
部分调整:UITabBarItem
播放gif显示比例有问题;UITabBarItem
只显示图片时,图片位置偏移;Badge
文字显示偏大UITableView
的cell
选中样式失效- 第三方SDK的闪退兼容问题
将所有问题归纳总结,得出以下几点解决方案的建议和示例代码,记录一下
1. UITextField
-
设置
placeholder
引起的闪退在
iOS 13
之前,设置placeholder
有三种方案:-
基于
KVO
简单粗暴的修改私有属性(iOS 13
禁用)[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
-
设置
attributedPlaceholder
属性textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"placeholder" attributes:@{ NSForegroundColorAttributeName: [UIColor darkGrayColor], NSFontAttributeName: [UIFont systemFontOfSize:13]}];
-
重写
UITextField
子类的drawPlaceholderInRect:
方法- (void)drawPlaceholderInRect:(CGRect)rect { [self.placeholder drawInRect:rect withAttributes:@{ NSForegroundColorAttributeName: [UIColor purpleColor], NSFontAttributeName: [UIFont systemFontOfSize:13]}]; }
适配
iOS 13
时,可根据实际情况选取后两种方案解决闪退问题。如果项目中重复使用了同一种UITextField
的样式,推荐使用第三种方案,创建UITextField
的子类。修改建议: 采用第二种方案,创建
UITextField
的Category
文件,里面封装好修改placeholder
的方法,后续修改都可统一直接调用这些方法// UITextField+CIPlaceholder.m文件 #import "UITextField+CIPlaceholder.h" @implementation UITextField (CIPlaceholder) - (void)setPlaceholderFont:(UIFont *)font { [self setPlaceholderColor:nil font:font]; } - (void)setPlaceholderColor:(UIColor *)color { [self setPlaceholderColor:color font:nil]; } - (void)setPlaceholderColor:(nullable UIColor *)color font:(nullable UIFont *)font { if ([self checkPlaceholderEmpty]) { return; } NSMutableAttributedString *placeholderAttriString = [[NSMutableAttributedString alloc] initWithString:self.placeholder]; if (color) { [placeholderAttriString addAttribute:NSForegroundColorAttributeName value:color range:
-