How to set a custom view's intrinsic content size in Swift?

前端 未结 2 1287
走了就别回头了
走了就别回头了 2020-12-07 13:19

Background

I am making a vertical label to use with traditional Mongolian script. Before I was just rotating a UILabel but there were s

2条回答
  •  一整个雨季
    2020-12-07 14:14

    Example of a "view with intrinsic height" ...

    @IBDesignable class HView: UIView {
    
        @IBInspectable var height: CGFloat = 100.0
    
        override var intrinsicContentSize: CGSize {
            return CGSize(width: 99, height: height)
            // if using in, say, a vertical stack view, the width is ignored
        }
    
        override func prepareForInterfaceBuilder() {
             invalidateIntrinsicContentSize()
        }
    }
    

    which you can set as an inspectable

    Since it has an intrinsic height, it can (for example) be immediately inserted in a stack view in code:

    stack?.insertArrangedSubview(HView(), at: 3)
    

    In contrast, if it was a normal view with no intrinsic height, you'd have to add a height anchor or it would crash:

    let v:UIView = HView()
    v.heightAnchor.constraint(equalToConstant: 100).isActive = true
    stack?.insertArrangedSubview(v, at: 3)
    

    Note that in ...

    the important special case of a stack view:

    • you set only ONE anchor (for vertical stack view, the height; for horizontal the width)

    so, setting the intrinsic height works perfectly, since:

    • the intrinsic height indeed means that the height anchor specifically will be set automatically if needed.

    Remembering that in all normal cases of a subview, many other anchors are needed.

提交回复
热议问题