简体   繁体   中英

How to set stack view height according to its subviews height?

I have a requirement to scroll six different type of view, Each view has different size, One of the views is: About Me. In About Me, I have to show the title (ie ABOUT ME) and text below it and label height should be according to text height.

Till Now I have designed this requirement as:

Root View - Stack View * Item 1 with fix height * Item 2 with fix height * UIView as About Me: - Label as title - Label as text with max lines set to 0 and width equals to container width.

The problem is: I can not set fix height of about me UIView and it does not resize according to label text. Please suggest the appropriate solutions.

Hi you can get the intrinsic height of the stackView like this:

let size = stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

I know Im kinda late to reply to this message. But I had the same issue and I found this piece of code. Thought anyone who looking for this might be useful :)

I don't think that you declare your problem clearly. The first thing I want to point out is that UIStackView can infer its size by the size of its arranged subview. But you must first confirm that the constraints added to the subviews are proper. So if you don't get the resizing effect you want, you must be missing something. Maybe you're not making the reasonable constraints.

To clarify your situation, you'd better add some screenshot of your constraints added to your 'About Me' view. By the way, what's the axis of your UIStackView ?

I don't know either of these. So I have to make some assumption for me to explain more about your problem.

  • The axis of your UIStackView is UILayoutConstraintAxisVertical .
  • And your UIStackView (or all of your content) has a fixed width.

With the above conditions, Defining a view that its height is decided by its text will be simple. Because UILabel doesn't have to have a fixed size. You only need to specify its width(or specify its leading and trailing to its superview), and its height will be automatically computed based on its font and content.

Your About Me view has two label, so you should
Make sure of these things:

  • Title label: The top, leading, trailing constraints to the super view. and the bottom gap to the subtitle label(whatever you call).
  • Subtitle label: The leading, trailing, bottom, constraints to the super view. and the top gap to the title label.

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