如何通过代码设置UIButton的Attributes Inspector中的Background属性
你在Interface Builder的Attributes Inspector中看到的Background属性,本质是iOS 15及以上版本推出的UIButton新样式体系中UIButtonConfiguration结构体的background字段,类型为UIBackgroundConfiguration,和旧版的backgroundColor、setBackgroundImage:forState:属于两套独立的渲染逻辑,单独设置旧版属性不会覆盖该配置的效果。
实现步骤
- 首先需要给UIButton指定基于配置的样式(如果是旧版初始化方式需要手动关联配置)
// Swift 示例:初始化时指定配置 let button = UIButton(configuration: .plain())
// Objective-C 示例:初始化时指定配置 UIButton *button = [UIButton buttonWithConfiguration:[UIButtonConfiguration plainConfiguration] primaryAction:nil];
- 取出配置修改background属性后赋值回按钮即可
// Swift 示例:修改背景配置 var config = button.configuration // 设置背景填充色 config?.background.backgroundColor = .systemBlue // 设置背景描边颜色 config?.background.strokeColor = .white // 设置背景描边宽度 config?.background.strokeWidth = 1 // 设置背景圆角 config?.background.cornerRadius = 8 // 设置背景内边距 config?.background.customInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) // 赋值回按钮生效 button.configuration = config
// Objective-C 示例:修改背景配置 UIButtonConfiguration *config = button.configuration; config.background.backgroundColor = [UIColor systemBlueColor]; config.background.strokeColor = [UIColor whiteColor]; config.background.strokeWidth = 1; config.background.cornerRadius = 8; config.background.customInsets = UIEdgeInsetsMake(8, 16, 8, 16); button.configuration = config;
注意事项
- 该属性仅支持iOS 15.0+、iPadOS 15.0+系统版本,需要适配更低版本时可使用旧版的
backgroundColor、layer.cornerRadius、setBackgroundImage:forState:组合实现相同效果 - 已经设置过
configuration的按钮,旧版背景相关属性会被配置覆盖,不会生效 - 如果需要实现按钮不同状态(选中、高亮等)下的背景差异,可以通过
configurationUpdateHandler动态修改配置:
button.configurationUpdateHandler = { button in var config = button.configuration // 高亮状态下背景色变深 config?.background.backgroundColor = button.isHighlighted ? .systemBlue.withAlphaComponent(0.7) : .systemBlue button.configuration = config }
内容的提问来源于stack exchange,提问作者Stephen501
相关产品推荐
相关产品推荐

