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

如何为UIBarButtonItem设置背景色并调整按钮尺寸?

查看BarButton示例图

实现方案

默认直接给UIBarButtonItem设置系统图片时,会自动继承导航栏的tintColor,且内置尺寸固定,无法直接自定义背景和大小,通过自定义视图作为UIBarButtonItem的载体即可实现目标效果,两种常用场景的实现代码如下:

UIKit 实现

// 1. 创建自定义按钮,指定固定尺寸
let customAddButton = UIButton(type: .custom)
customAddButton.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
// 2. 设置背景色和圆角
customAddButton.backgroundColor = .systemBlue
customAddButton.layer.cornerRadius = 8
customAddButton.clipsToBounds = true

// 3. 配置系统图片,调整大小权重
let symbolConfig = UIImage.SymbolConfiguration(pointSize: 16, weight: .bold)
let plusImage = UIImage(systemName: "plus.color.fill", withConfiguration: symbolConfig)
// 4. 给按钮设置图片,调整tint色为白色
customAddButton.setImage(plusImage, for: .normal)
customAddButton.tintColor = .white

// 5. 包装为BarButtonItem赋值给导航栏
let addBarItem = UIBarButtonItem(customView: customAddButton)
navigationItem.rightBarButtonItem = addBarItem

如果需要保留plus.color.fill本身的原生多色效果,不被tintColor覆盖,可在生成图片时添加渲染模式配置:
let plusImage = UIImage(systemName: "plus.color.fill", withConfiguration: symbolConfig)?.withRenderingMode(.alwaysOriginal)

SwiftUI 实现

NavigationStack {
    Text("页面内容")
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    // 按钮点击逻辑
                } label: {
                    Image(systemName: "plus.color.fill")
                        .font(.system(size: 16, weight: .bold))
                        .foregroundColor(.white)
                        .frame(width: 36, height: 36)
                        .background(.blue)
                        .cornerRadius(8)
                }
            }
        }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:54:03