tableView/scrollView默认内边距问题(contentInsetAdjustmentBehavior属性)

在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的绿色的方块, 我们会看到如下图的效果:


存在默认内边距.png

如果要消除该默认内边距, 需要在viewDidLoad方法中添加:

if (@available(iOS 11.0, *)) {
        scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

添加后效果如下:


去掉默认内边距.png

关于contentInsetAdjustmentBehavior属性

scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

可以参照:https://www.jianshu.com/p/b42030a37953

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容