UIView 子类在初始化时固定高度

UIView Subclass fixed height on initialization

我有一个 UIButton 子类,它的高度需要 80pt,但在 UIStackView 等中使用时宽度表现正常...这如何在子类中实现。

下面的代码成功改变了高度,但是UIStackView没有调整布局来准确高度:

class MenuSelectionButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 5.0
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        var newFrame = frame
        newFrame.size.height = 80
        frame = newFrame
    }

}

工作代码:

class MenuSelectionButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 5.0
        addHeightConstraint()
    }

    private func addHeightConstraint () {
        let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 80)
        NSLayoutConstraint.activateConstraints([heightConstraint])
    }

}

将按钮的高度限制为 80,让自动布局处理它。

或者,由于您使用的是 UIButton 的自定义子类,因此将 instrinsicContentSize 重写为 return 80 的高度:

import UIKit

@IBDesignable
class MenuSelectionButton: UIButton {

    // Xcode uses this to render the button in the storyboard.
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    // The storyboard loader uses this at runtime.
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override func intrinsicContentSize() -> CGSize {
        return CGSize(width: super.intrinsicContentSize().width, height: 80)
    }

    private func commonInit() {
        self.layer.cornerRadius = 5.0
    }

}