iOS 11新特性与适配
iOS 11正式发布了,下面整理了一些该版本下的特点还有如何进行兼容适配工作。
1. UIView变化
1.1. 更加方便的RTL边距设置
在之前的系统中我们会使用layoutMargins
来获取和设置控件显示内容部分的边缘与控件边缘的距离。在iOS 11中,新增directionalLayoutMargins
属性来指定边距。这两个属性的结构定义如下:
typedef struct UIEdgeInsets {
CGFloat top, left, bottom, right;
} UIEdgeInsets;
typedef struct NSDirectionalEdgeInsets {
CGFloat top, leading, bottom, trailing;
} NSDirectionalEdgeInsets
从结构上看主要是将UIEdgeInsets
结构的left
和right
调整为NSDirectionalEdgeInsets
结构的leading
和trailing
。这一调整主要是为了Right To Left(RTL)语言下可以进行自动适配,例如:要实现文本每行尾部边距设置为30px,在以前做法则需要判断语言来区分哪些是RTL语言,然后再做设置,如:
if ([UIView userInterfaceLayoutDirectionForSemanticContentAttribute:self.view.semanticContentAttribute] == UIUserInterfaceLayoutDirectionRightToLeft)
{
// Right to left 语言下每行尾部在左边
self.view.layoutMargins.left = 30;
}
else
{
self.view.layoutMargins.right = 30;
}
iOS 11 后则可以一步到位,如:
self.view.directionalLayoutMargins = NSDirectionalEdgeInsetsMake(0, 0, 0, 30);
注:测试时需要添加RTL本地化语言才能看到效果
1.2. 安全区域
在iOS 11中新增了安全区域的概念,目的是告诉开发者在这个区域下绘制的内容的显示才是有效的,否则会存在被遮挡的情况(特别是iPhoneX那帅气的刘海)。在UIView中新增safeAreaLayoutGuide
和safeAreaInsets
来获取屏幕的安全区域(对于frame布局时是很有用的)。如图所示:
举个例子,在一个空白的UIViewController
中,分别在viewDidLoad
和viewDidAppear
方法中输出view.safeAreaInsets
观察边距情况,代码如下:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *edgeStr = NSStringFromUIEdgeInsets(self.view.safeAreaInsets);
NSString *layoutFrmStr = NSStringFromCGRect(self.view.safeAreaLayoutGuide.layoutFrame);
NSLog(@"viewDidLoad safeAreaInsets = %@, layoutFrame = %@", edgeStr, layoutFrmStr);=
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSString *edgeStr = NSStringFromUIEdgeInsets(self.view.safeAreaInsets);
NSString *layoutFrmStr = NSStringFromCGRect(self.view.safeAreaLayoutGuide.layoutFrame);
NSLog