Swift中如何修改UIButton背景色?使用frame初始化后设置无效怎么办
问题原因
- iOS 15及以上系统中,通过
UIButton(frame:)初始化的按钮默认启用了UIButtonConfiguration配置体系,直接对backgroundColor属性赋值会被配置中的背景设置覆盖,因此无法生效。
解决方案
方法1:禁用按钮的自动配置(适配原有旧代码)
在初始化按钮后第一行加上button.configuration = nil,即可恢复旧版UIButton的属性设置逻辑,原来的背景色、文字样式设置都会正常生效,修改后的代码如下:
var index:Int = 0; let heightView = view.frame.height for item in arr { let button = UIButton(frame: CGRect(x: index, y: 0, width: item.count * 11, height: Int(heightView))) // 新增这一行即可 button.configuration = nil index = index + item.count * 11 button.setTitleColor(.black, for: .normal) button.setTitle(item, for: .normal) button.backgroundColor = UIColor.red button.contentHorizontalAlignment = .center button.contentVerticalAlignment = .center button.layer.cornerRadius = 10 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.red.cgColor view.addSubview(button) print(button.frame) }
方法2:明确指定按钮类型为custom
初始化时直接指定按钮类型为custom,也可以避免默认配置的干扰:
// 把原来的UIButton(frame:)初始化替换为下面两行 let button = UIButton(type: .custom) button.frame = CGRect(x: index, y: 0, width: item.count * 11, height: Int(heightView)) // 后续原有代码保持不变
方法3:使用新的configuration体系设置样式
如果要适配iOS15之后的新特性,直接通过configuration配置所有样式即可:
let button = UIButton(frame: CGRect(x: index, y: 0, width: item.count * 11, height: Int(heightView))) var config = UIButton.Configuration.plain() config.title = item config.baseForegroundColor = .black config.background.backgroundColor = .red config.background.strokeColor = .red config.background.strokeWidth = 1 config.background.cornerRadius = 10 button.configuration = config
内容的提问来源于stack exchange,提问作者anhhung
相关产品推荐
相关产品推荐

