我的项目中有几个格式相同的按钮。将相同格式应用于多个按钮的最佳方法是什么,所以我不必每次都手动执行此操作?
感谢您的帮助!
答案 0 :(得分:0)
您可以继承UIButton并使用它。
这是UIButton子类的一些示例代码,以及以编程方式创建两个新按钮。如果您正在使用故事板,请在视图中添加UIButton,然后在Identity Inspector中将其类更改为自定义子类。
UIButton子类:
class OneButtonToRuleThemAll: UIButton {
// This is used when you create your view programatically.
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
// This is used when the view is created from a storyboard or a Nib file.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
// This is optional.
// You can use it to initialize your view programatically with specific parameters.
convenience init(frame: CGRect, title: String) {
self.init(frame: frame)
setTitle(title, for: .normal)
}
// Do your custom configuration here
func commonInit() {
clipsToBounds = true
let backgroundImage = UIImage(from: .green)
setBackgroundImage(backgroundImage, for: .normal)
setTitleColor(.white, for: .normal)
titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
}
// You may need to perform some of your configurations outsite the initializers.
// You can use other methods from the UIView lifecycle for this.
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = frame.height/2
}
}
这对于此答案并不重要,但如果您想更改按钮的背景,则应使用UIImage而不是设置背景颜色,以便使用高光效果。此扩展可用于从UIColor创建图像:
extension UIImage {
convenience init?(from color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
以编程方式创建两个按钮:
@IBOutlet weak var buttonsStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Using the designated initializer
let button = OneButtonToRuleThemAll(frame: CGRect.zero)
button.setTitle("Button From Code", for: .normal)
buttonsStackView.addArrangedSubview(button)
// Using the convenience initializer
let button2 = OneButtonToRuleThemAll(frame: CGRect.zero, title: "But Wait, There's More!")
buttonsStackView.addArrangedSubview(button2)
}