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

iOS 16.2中如何修改navigationItem与barButtonItem背景色?

iOS 16.2 导航栏与自定义BarButtonItem样式设置方案

一、设置导航栏(NavigationBar)背景色

iOS 16+ 废弃了部分旧版导航栏样式API,Runtime Attributes也不再支持直接修改背景色,需通过UINavigationBarAppearance统一配置:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 创建导航栏外观配置实例
    let navAppearance = UINavigationBarAppearance()
    // 设置导航栏背景色
    navAppearance.backgroundColor = .systemTeal
    // 可选:移除导航栏底部阴影线
    navAppearance.shadowColor = .clear
    
    // 为导航栏的不同显示状态应用配置
    navigationController?.navigationBar.standardAppearance = navAppearance
    navigationController?.navigationBar.scrollEdgeAppearance = navAppearance
    navigationController?.navigationBar.compactAppearance = navAppearance
}

二、为"Save"按钮添加背景色与圆角

系统默认UIBarButtonItem无法直接设置背景色和圆角,需通过自定义UIButton作为其customView实现:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 构建自定义Save按钮
    let saveBtn = UIButton(type: .system)
    saveBtn.setTitle("Save", for: .normal)
    saveBtn.setTitleColor(.white, for: .normal)
    // 设置按钮背景色
    saveBtn.backgroundColor = .systemBlue
    // 设置圆角
    saveBtn.layer.cornerRadius = 8
    // 调整内边距避免文字贴边
    saveBtn.contentEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12)
    
    // 绑定点击事件(替换为你的业务逻辑方法)
    saveBtn.addTarget(self, action: #selector(handleSave), for: .touchUpInside)
    
    // 将自定义按钮转为BarButtonItem并添加到导航栏右侧
    let saveBarItem = UIBarButtonItem(customView: saveBtn)
    navigationItem.rightBarButtonItem = saveBarItem
}

@objc private func handleSave() {
    // 此处编写保存逻辑
}

额外说明

  • 若需全局统一导航栏样式,可在AppDelegate或SceneDelegate中对UINavigationBar.appearance()进行全局配置;
  • 自定义按钮时可按需调整字体大小、内边距等参数,适配不同设备显示;
  • 确保导航栏由UINavigationController管理,否则需直接对当前页面的导航栏实例进行配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:52:06