在将遗留代码更新为现代标准的背景下,我遇到了需要重构 UIButton 创建和配置过程的场景。原实现如下:
let button = UIButton()
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
button.setImage(UIImage(named: "MyIcon"), for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.imageEdgeInsets = UIEdgeInsets(top: -8, left: -40, bottom: -8, right: 0)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -60, bottom: 0, right: 0)
button.translatesAutoresizingMaskIntoConstraints = false
button.sizeToFit()
我希望获得有关将此代码转换为使用 iOS 15 中引入的 UIButton.Configuration 范例的指导,以确保按钮的视觉布局和交互行为与原始实现保持一致。需要什么方法或特定配置才能实现这一目标?
我建议添加按钮的图像,以便更轻松地创建代码,但根据您的解释......
UIButton.Configuration
包含其他方法(例如 setTitle(_:for:)
)可用的所有自定义选项,并且可以替代您提供的所有这些方法。
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
var configuration = UIButton.Configuration.filled()
configuration.baseBackgroundColor = .link // color of the button background
configuration.baseForegroundColor = .white // color of the text and image
configuration.image = UIImage(systemName: "star")
configuration.title = "Star Button"
configuration.imagePlacement = .leading
configuration.contentInsets.leading = 40
configuration.imagePadding = 20
configuration.titlePadding = 20 // 20 starting from the end of the image
button.configuration = configuration
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
我强烈建议您查看这些网站,因为它们在大多数情况下都有示例: