UIView dynamic height inside UIStackView

帅比萌擦擦* 提交于 2019-12-02 17:54:27

问题


I currently have a Stack View setup with a bunch of different objects inside of it, and I'm trying to add a view to it.

The view will have a dynamic number of labels added inside of it programmatically at run-time.

When I put the view inside of the stack view, I get errors with the constraints, which get fixed by adding a height constraint.

However, I don't know the height of the view initially so I can't constrain this.

Is there any way to have a UIView inside of a StackView auto-resize based on it's content size? I thought this would be automatic, but when I don't put a height constraint, the view doesn't show up


回答1:


You don't have to put a content view inside the stackview to add the elements to it , you need to hook the stackview with only ( leading , trailing , top) constraints to the superView

then add elements with

stack.addArrangedSubview(view)

the most important thing is that the elements you add must have an intrinstic content-size like label and button , and if not then add a height with

someView.heightAnchor.constraint(equalToConstant:<#setValue#>).isActive = true

with distribution set to Fill




回答2:


Steps to add custom UIView with dynamic height inside UIStackView

  1. Add UIStackView to superview in IB and add top, bottom, leading and trailing constraints.
  2. In case IB is throwing any error for constraint, just set intrinsic size for UIStackView as PlaceHolder with some dummy size. This will fix UIStackView position in IB but this will automatically change at run time as per auto layout.
  3. Create instance of CustomUIView as below

    Bundle.main.loadNibNamed(nibName, owner: self, options: nil).first as! CustomUIView

  4. Add UIView to UIStackView as below.

    stackView.addArrangedSubview(customView)

  5. This will add custom UIView to UIStackView and it will expand/collapse as per xib content and constraints. Just make sure your xib has proper constraints as per auto layout guidelines.


来源:https://stackoverflow.com/questions/51936947/uiview-dynamic-height-inside-uistackview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!