You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Objective-C中为iPhone X的UIViewController不安全区域设置背景色

嘿,这个问题我之前做项目的时候也碰到过,iPhone X及以后机型的安全区域适配确实得注意几个细节,下面给你几种Objective-C的实现方案,你可以根据自己的需求来选:

方法1:统一设置整个屏幕(含不安全区域)的背景色

如果你的需求是让整个屏幕(包括顶部状态栏区域、底部Home Indicator区域)用同一种背景色,这是最简单的方案:

默认情况下,UIViewController的edgesForExtendedLayout属性值是UIRectEdgeAll,意味着控制器的view会自动延伸到屏幕边缘(覆盖不安全区域)。你只需要在viewDidLoad里直接设置view的背景色即可:

- (void)viewDidLoad {
    [super viewDidLoad];
    // 替换成你需要的颜色
    self.view.backgroundColor = [UIColor systemTealColor];
}

如果你的控制器嵌套在导航栏或TabBar中,且导航栏/TabBar是半透明状态,这个方法依然有效——view会延伸到bar的下方,背景色会透过半透明的bar显示出来。

方法2:单独给顶部/底部不安全区域设置自定义背景色

如果你需要给顶部状态栏区域、底部Home Indicator区域分别设置不同的背景色,可以通过添加自定义UIView+Auto Layout的方式实现:

给顶部不安全区域设置背景色

- (void)setupTopSafeAreaBackground {
    UIView *topBgView = [[UIView alloc] init];
    topBgView.backgroundColor = [UIColor redColor]; // 自定义顶部背景色
    topBgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:topBgView];
    
    // 添加约束,让view刚好覆盖顶部不安全区域
    [NSLayoutConstraint activateConstraints:@[
        [topBgView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
        [topBgView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [topBgView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [topBgView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor]
    ]];
}

给底部不安全区域设置背景色

- (void)setupBottomSafeAreaBackground {
    UIView *bottomBgView = [[UIView alloc] init];
    bottomBgView.backgroundColor = [UIColor blueColor]; // 自定义底部背景色
    bottomBgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:bottomBgView];
    
    // 添加约束,让view刚好覆盖底部不安全区域
    [NSLayoutConstraint activateConstraints:@[
        [bottomBgView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
        [bottomBgView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
        [bottomBgView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor],
        [bottomBgView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor]
    ]];
}

最后在viewDidLoad里调用这两个方法即可:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTopSafeAreaBackground];
    [self setupBottomSafeAreaBackground];
}
方法3:配合导航栏设置顶部不安全区域背景色

如果你的控制器在UINavigationController中,想要顶部不安全区域(状态栏)和导航栏同色,可以通过配置导航栏的属性实现:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏的背景色
    self.navigationController.navigationBar.barTintColor = [UIColor purpleColor];
    // 若需要不透明的导航栏,设置translucent为NO(此时控制器的view不会延伸到导航栏下方)
    self.navigationController.navigationBar.translucent = NO;
    
    // 要是你想保留导航栏的半透明效果,同时让顶部不安全区域和导航栏同色,建议用方法2的自定义view方案
}

内容的提问来源于stack exchange,提问作者Yogesh Dalavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 07:05:37