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

如何修改iOS开发中UIButton控件的背景颜色?

UIButton 背景色修改方案

基础全局背景色设置

UIKit 中 UIButton 自带backgroundColor属性,默认值为nil对应透明效果,和你观察到的其他按钮默认表现一致,直接赋值即可修改全局背景色:

// 全局设置背景色,对所有按钮状态生效
subscribeButton.backgroundColor = .systemBlue
// 需要恢复透明时赋值为nil即可
// subscribeButton.backgroundColor = nil

不同状态自定义背景色

如果需要针对normal/highlighted/disabled等不同按钮状态显示不同背景色,需要先生成对应颜色的纯色图片,再调用setBackgroundImage(_:for:)方法实现:
首先新增一个UIImage扩展快速生成纯色图:

extension UIImage {
    static func makePureColorImage(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let resultImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        UIGraphicsEndImageContext()
        return resultImage
    }
}

之后在你现有的方法中调用即可:

func updateNewButton() {
    if newButton == true {
        let buttonFont = self.ButtonFont
        self.subscribeButton.SetAttributedTitle(title: StoreKit.sharedInstance.ButtonStateText, withFont: buttonFont, textColor: storeBackground, for: .normal)
        // 示例:普通状态设为蓝色,高亮状态设为半透蓝色
        self.subscribeButton.setBackgroundImage(UIImage.makePureColorImage(color: .systemBlue), for: .normal)
        self.subscribeButton.setBackgroundImage(UIImage.makePureColorImage(color: .systemBlue.withAlphaComponent(0.7)), for: .highlighted)
    }
}

高版本系统简化方案

iOS 15及以上版本可以用UIButton.Configuration直接设置,不需要手动生成纯色图片:

if #available(iOS 15.0, *) {
    var config = subscribeButton.configuration ?? .plain()
    config.baseBackgroundColor = .systemBlue
    subscribeButton.configuration = config
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:57:01