简体   繁体   中英

Set Height of UIView on the basis of the content inside

I am adding an OverlayView to a Controller. I have set all the constraints to my OverlayView except the bottom constraint. I have a button at the end of my view. I am setting the size of the OverlayView as button.frame.maxY + margin . But it's not setting up the right height.

override func layoutSubviews() {
    sizeToFit()
    var sizeThatFits: CGSize = bounds.size
    sizeThatFits.width = UIScreen.main.bounds.size.width - popupSizeHorizontalMargin
    sizeThatFits.height = getStartedButton.frame.maxY + popupBottomMargin
    let newFrame = CGRect(x: popupOriginX, y: bounds.midY - sizeThatFits.height/2, width: sizeThatFits.width, height: sizeThatFits.height)
    frame = newFrame
}

The overlay view or outer view can calculate its height based on the size of elements inside it and their intrinsic size. Instead of specifying height constraint for overlay view or bottom constraint, add bottom constraint of overlay view to the last element inside the overlay view. This will satisfy the constraints and your overlay view will expand based on its contents.

Simply ctrl drag from your overlay view to the last inner view and select Bottom Space to Container.

在此输入图像描述

This can be accomplished according to this [inner elements are example]

OverlayView
           -> label ------> top to overlayView ,left,right
           -> button -----> top to label , left , right
           -> label  -----> top to button , left , right , bottom to overlayView

You need to override intrinsicContentSize in UIView and return your custom size:

class YourCustomView: UIView {

  override var intrinsicContentSize: CGSize {
    var someYourSize = CGSize()
    // ... calculate your size
    return someYourSize
  }

}

It will automatically update YourCustomView size to your custom calculated size using autolayout or when you want to update size manually via code - call invalidateIntrinsicContentSize() on YourCustomView object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM