iOS11的Safe Area的变化让适配变得很头痛。今天就发现一个奇怪的bug,是由safe area的变化引起的。
直接上代码:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
}
#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
cell.backgroundColor = [UIColor redColor];
return cell;
}else{
UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
cell.backgroundColor = [UIColor greenColor];
return cell;
}
}
其余的省略...
分别在6P iOS8.4、6PiOS11、iphoneX上跑

会发现,只有iOS11以下的设备能够做到“顶头”布局。
别急,看下原因:
- (void)viewDidLoad{
......
NSLog(@"%d",self.tableView.contentOffset.y);
[self.view addSubview:self.tableView];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSLog(@"%d",self.tableView.contentOffset.y);
}
iphoneX(iOS11)在不滑动的情况下打出的log:

比iOS8.4多了在scrollViewDidScroll的两次log,以下为打断点看到的栈信息(两次一样)。可见iOS11为挡住safe area的tableView自动调整了contentInset。

网友评论