带有附加标签的UIButton子类-如何居中

时间:2019-05-20 16:41:43

标签: swift uibutton uilabel subclass subview

我想对UIButton进行子类化,并在标题标签下添加一个附加标签。标签应准确居中,并在标题标签下方10px。它还应该在“界面”构建器中的任何调整大小上进行更新。我怎么能做到这一点。目前我有:

@IBDesignable
class MyButton: UIButton {

    let additionalLabel = UILabel()
    @IBInspectable var additionalValue: String = "Test" {
        didSet {
            additionalLabel.text = additionalValue
        }
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    func commonInit(){
        updateView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        updateView()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // Set label size and position
        additionalLabel.frame.size = CGSize(width: frame.width, height: 30)
        additionalLabel.frame.origin = CGPoint(x: 0, y: 0)
        additionalLabel.center.x = self.center.x
        additionalLabel.center.y = self.center.y + 10
    }

    func updateView() {
        setTitle("abc", for: .normal)
        additionalLabel.text = additionalValue
        addSubview(additionalLabel)
    }

}

但是附加标签没有完全居中,并且在IB中调整按钮大小时,它不会调整。

0 个答案:

没有答案