我正在尝试自己的自定义UIButton。我继承了UIButton类,并尝试添加一些功能,这是我的代码:
import UIKit
class CustomButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
setGradientBackground()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
private func setup() {
layer.cornerRadius = 8
}
private func setGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [UIColor.yellow.cgColor, UIColor.blue.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}
我将其链接到我的IBOutlet:
@IBOutlet weak var myButton: CustomButton!
没有任何内容!
答案 0 :(得分:2)
如果要在情节提要中添加按钮,则调用的初始化程序为init?(coder aDecoder: NSCoder)
,而不是init(frame: CGRect)
,因此需要添加…
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
setGradientBackground()
}
答案 1 :(得分:1)
使用func awakeFromNib()
:
class CustomButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
setup()
setGradientBackground()
}
private func setup() {
layer.cornerRadius = 8
}
private func setGradientBackground() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [UIColor.yellow.cgColor, UIColor.blue.cgColor]
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
}
}