在scrollView/tableView等可互动控件中, 控制器隐藏导航栏后, 可滑动控件默认布局会有一个内边距, 顶部会把状态栏的高度空出来.
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:NO];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:scrollView];
scrollView.backgroundColor = [UIColor purpleColor];
scrollView.contentSize = CGSizeMake(0, [UIScreen mainScreen].bounds.size.height*2);
UIView *box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
box.backgroundColor = [UIColor greenColor];
[scrollView addSubview:box];
}
以上代码是一个背景色为紫色的scrollView, 该scrollView添加了一个y=0的绿色的方块, 我们会看到如下图的效果:
如果要消除该默认内边距, 需要在viewDidLoad方法中添加:
if (@available(iOS 11.0, *)) {
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
self.automaticallyAdjustsScrollViewInsets = NO;
}
添加后效果如下:
关于contentInsetAdjustmentBehavior属性
scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;