自定义按钮不显示标题

时间:2019-08-22 12:09:08

标签: swift uibutton subclass

我在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))

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

好吧,我明白了。您应该在自己的layoutSubviews()内部调用 super.layoutSubviews(),这样内部视图(如标题标签)才能正确显示。