如何在UIButtonConfiguration生效时禁用UIButton高亮状态的标题变色?
解决按钮高亮时标题保持纯白色的问题
你需要在UIButton的配置中显式指定高亮状态下的前景色,因为默认的filled类型配置会在按钮高亮时自动调暗前景色。
修改方案
在你的UIButton扩展的便利初始化方法里,添加一行代码指定高亮状态的前景色:
extension UIButton { convenience init( radius: CGFloat = 0, title: String? = nil, backgroundColor: UIColor? = nil, foregroundColor: UIColor = .white, font: UIFont? = nil ) { var configuration = UIButton.Configuration.filled() configuration.baseForegroundColor = foregroundColor // 添加这行:指定高亮状态下的前景色与默认一致 configuration.highlightedForegroundColor = foregroundColor configuration.title = title configuration.background.cornerRadius = radius configuration.cornerStyle = .fixed configuration.contentInsets = .zero configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in var outgoing = incoming outgoing.font = font return outgoing } configuration.baseBackgroundColor = backgroundColor configuration.background.backgroundColor = backgroundColor self.init(configuration: configuration) } }
原理说明
默认的filled配置会为高亮状态应用一个自动生成的前景色(通常是默认前景色的暗化版本),通过显式设置highlightedForegroundColor,可以强制按钮在高亮时使用你指定的纯白色。
如果希望按钮在所有交互状态(比如选中、禁用)下都保持白色标题,也可以统一设置configuration.foregroundColor = .white,不过这会覆盖所有状态的前景色配置,可根据需求选择。
内容的提问来源于stack exchange,提问作者kunass2
相关产品推荐
相关产品推荐

