iosswiftuiviewnslayoutconstraint

Default height of UIView with constraints (auto layout)


When you build an UI programatically with swift and constraints, you can notice that most views have some height or width, and you don't need to define it. For example UILabel, if you make constraints to top, left and right anchor, it is visible without setting height. And that's my question - Making a custom view based on UIView, how can I set this default hight for it?


Solution

  • The "default" width and height are determined by intrinsicContentSize. You can override this property in you custom UIView.

    For example, here is a UIView subclass with an intrinsic height:

    class MyView: UIView {
        override var intrinsicContentSize: CGSize {
            // UIView.noIntrinsicMetric for the width, because I don't want this to have an intrinsic width.
            CGSize(width: UIView.noIntrinsicMetric, height: 20)
        }
    }
    

    Then, you can see that AutoLayout correctly lays this out, even without a height constraint:

    let myView = MyView()
    myView.translatesAutoresizingMaskIntoConstraints = false
    myView.backgroundColor = .green
    view.addSubview(myView)
    NSLayoutConstraint.activate([
        myView.widthAnchor.constraint(equalToConstant: 100),
        myView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        myView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    ])