IOS11新特性与兼容适配

2020-01-21 02:41:36王冬梅

之前的系统中,如果你的滚动视图包含在一个导航控制器下,系统会自动地调整你的滚动视图的contentInset。而iOS 11新增adjustedContentInset属性取替之前contentInset的处理方式。这两者之间的关系如下图所示:

IOS11,新特性,兼容,适配

adjustedContentInset & contentInset

通过一个例子来验证这说法,代码如下:


- (void)viewDidLoad
{
[super viewDidLoad];

NSLog(@"viewDidLoad");
NSLog(@"self.tableView.contentInset = %@", NSStringFromUIEdgeInsets(self.tableView.contentInset));
NSLog(@"self.tableView.adjustedContentInset = %@", NSStringFromUIEdgeInsets(self.tableView.adjustedContentInset));
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];

NSLog(@"viewDidAppear");
NSLog(@"self.tableView.contentInset = %@", NSStringFromUIEdgeInsets(self.tableView.contentInset));
NSLog(@"self.tableView.adjustedContentInset = %@", NSStringFromUIEdgeInsets(self.tableView.adjustedContentInset));
}

执行后输出下面信息:


2017-09-20 11:54:09.361348+0800 Sample[1276:375286] viewDidLoad
2017-09-20 11:54:09.361432+0800 Sample[1276:375286] self.tableView.contentInset = {0, 0, 0, 0}
2017-09-20 11:54:09.361462+0800 Sample[1276:375286] self.tableView.adjustedContentInset = {0, 0, 0, 0}
2017-09-20 11:54:09.420000+0800 Sample[1276:375286] viewDidAppear
2017-09-20 11:54:09.420378+0800 Sample[1276:375286] self.tableView.contentInset = {0, 0, 0, 0}
2017-09-20 11:54:09.420554+0800 Sample[1276:375286] self.tableView.adjustedContentInset = {20, 0, 0, 0}

可见,tableView的adjustedContentInset自动改变了,但是contentInset的值是保持不变的。注:一定要是VC的根视图为UIScrollView或者其子类才能够得到adjustedContentInset的值,否则获取到的是空值。而且非根视图的滚动视图就会被安全区域所裁剪,看到的样式如下图所示:

IOS11,新特性,兼容,适配

样式效果对比

通过使用contentInsetAdjustmentBehavior属性可以控制 adjustedContentInset的变化。该属性为枚举类型,其定义如下:


typedef NS_ENUM(NSInteger, UIScrollViewContentInsetAdjustmentBehavior) {
UIScrollViewContentInsetAdjustmentAutomatic,
UIScrollViewContentInsetAdjustmentScrollableAxes, 
UIScrollViewContentInsetAdjustmentNever,
UIScrollViewContentInsetAdjustmentAlways, 
}

其中UIScrollViewContentInsetAdjustmentAutomatic与UIScrollViewContentInsetAdjustmentScrollableAxes一样,ScrollView会自动计算和适应顶部和底部的内边距并且在scrollView 不可滚动时,也会设置内边距;

UIScrollViewContentInsetAdjustmentNever表示不计算内边距;UIScrollViewContentInsetAdjustmentAlways则根据视图的安全区域来计算内边距。