如何修改iOS开发中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
相关产品推荐
相关产品推荐

