我在Swift中自定义了一个UIButton。但我无法正确显示标题。这是我的课程:
import UIKit
final class CustomButton: UIButton {
var cornerRs: Bool = false
override init(frame: CGRect){
super.init(frame: frame)
}
convenience init(bordercolor : CGColor = UIColor.black.cgColor,
backGroundColor : UIColor = UIColor.black, foreGroundColor : UIColor = UIColor.black,borderThickness : CGFloat = 1,borderRadius:Bool = false,title : String, font : UIFont = UIFont.preferredFont(forTextStyle: .body)) {
self.init(frame: .zero)
self.translatesAutoresizingMaskIntoConstraints = false
self.cornerRs = borderRadius
self.layer.borderWidth = borderThickness
self.layer.borderColor = bordercolor
self.setTitleColor(foreGroundColor, for: UIControl.State.normal)
self.setTitle(title, for: UIControl.State.normal)
self.backgroundColor = backGroundColor
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
setup()
}
func setup() {
self.clipsToBounds = true
self.layer.cornerRadius = (self.cornerRs) ? self.frame.size.height / 2.0 : 0
}
}
这是我的实例:
button = CustomButton(bordercolor: UIColor.blue.cgColor, backGroundColor: UIColor.blue, foreGroundColor: .white, borderThickness: 1, borderRadius: true, title: "Click here!", font: UIFont.preferredFont(forTextStyle: .headline))
我在这里做什么错了?
答案 0 :(得分:1)
好吧,我明白了。您应该在自己的layoutSubviews()内部调用 super.layoutSubviews(),这样内部视图(如标题标签)才能正确显示。