Swift中UIButton.configuration.contentInsets内边距无效怎么办
问题根源
通过UIButton(frame:)构造方法初始化的按钮,默认configuration属性为nil。代码中boton.configuration?.contentInsets = NSDirectionalEdgeInsets(...)是可选链调用,当configuration为nil时这行赋值逻辑不会执行,因此设置的内边距不会生效。
修复方法
你需要先为按钮创建configuration实例,再修改内边距属性,两种常用实现方式如下:
方式1:补全configuration初始化逻辑
在设置contentInsets前先给configuration赋值,修改后的代码:
lazy var botonDescarga : UIButton = { let boton = UIButton(frame: .zero) boton.setTitle("Descargar todo", for: .normal) boton.backgroundColor = .white boton.setTitleColor(UIColor(.black), for: .normal) boton.layer.cornerRadius = 5 boton.layer.borderWidth = 1 // 先初始化configuration,plain样式对应普通文本按钮 boton.configuration = .plain() // 此时configuration非空,内边距设置生效 boton.configuration?.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) return boton }()
方式2:初始化按钮时直接传入configuration
iOS 15及以上系统支持configuration构造方法,写法更简洁:
lazy var botonDescarga : UIButton = { // 提前配置好按钮边距属性 var config = UIButton.Configuration.plain() config.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) let boton = UIButton(configuration: config) boton.setTitle("Descargar todo", for: .normal) boton.backgroundColor = .white boton.setTitleColor(UIColor(.black), for: .normal) boton.layer.cornerRadius = 5 boton.layer.borderWidth = 1 return boton }()
注意点
- 如果项目需要兼容iOS 15以下版本,无法使用
configuration系列API,需通过旧版属性contentEdgeInsets设置按钮内边距 - 按钮一旦设置了
configuration,旧版的contentEdgeInsets、titleEdgeInsets、imageEdgeInsets属性会全部失效,排版、边距相关配置需要统一通过configuration调整
内容的提问来源于stack exchange,提问作者danifm1321
相关产品推荐
相关产品推荐

