【问题标题】:UIView Subclass fixed height on initializationUIView 子类在初始化时固定高度
【发布时间】:2016-06-23 00:29:31
【问题描述】:

我有一个 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])
    }

}

【问题讨论】:

    标签: swift uiview autolayout initialization subclass


    【解决方案1】:

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

    或者,由于您使用的是 UIButton 的自定义子类,请覆盖 instrinsicContentSize 以返回 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
        }
    
    }
    

    【讨论】:

    • 这需要在按钮子类中完成,以避免需要在按钮的每个实例中手动添加约束 - 这可能吗?
    • 根据您定义init(coder:) 的事实,我假设您正在从情节提要加载按钮。您可以在情节提要中创建约束。
    • 按钮没有随附的 XIB 文件 - 它是 UIButton 的直接子类。这些按钮正在添加到其他 XIB 文件中,并且可以在那里添加约束,但是以编程方式添加约束要容易得多,如我的编辑问题所示。
    • 我已经用另一个您可能更喜欢的解决方案更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多