简体   繁体   中英

UITableView inside a UIStackView height constraint issue

Requirement:

Our application has a pattern where many screens have a number of UILabels on the top and a single UITableView bellow them which, when present, is always the last element on the page and expands right to the bottom of the screen. Because the pages are dependent on user specific data, we don't know upfront how many labels we need to display. Also, in some case when there is no data to display in UITableView, we simply want hide it.

My implementation (that doesn't work):

Because of the dynamic nature of the page, I thought that wrapping all the UILabels and the UITableView in UIStackView and later manipulating the elements visibility (ie the isHidden property) in code is the way to go. I pinned all the corners of the UIStackView to the corners of the SuperView, except the bottom constraint, which I made greater than or equal of UIStackView bottom constraint. This was done in order to make sure that in case the UITableView is hidden, the UIStackView does not take the whole screen as it tends to display the labels in the middle of the screen when it does so. Basically if the UITableView is visible, I want the UIStackView to take the whole page, else, just the space it needs to display the labels.

The issues:

演示问题的示例应用程序 高度限制问题

The AutoLayout has a problem figuring out the height of the UITableView. I can think of two solutions to this:

  1. Change the UIStackView bottom constant to be 'Equal' rather then 'Greater Than Or Equal'. This way however the UIStackView will always take the whole screen height, not something I want when the UITableView is hidden.
  2. Manually specify the height constraint of UITableView. I don't want to do this as I don't know upfront what will be the needed height from the top of the TableView to the bottom of the screen. I think this is not too hard to do in code, but I was hoping for a more elegant solution.

Interesting observation:

Unlike the UITableView, the UILabels don't seem to have the same problem with height constraints as the UITableView. I'm not 100% sure why this is but my guess is that UILabels know in advance their height (probably via intrinsicContentSize()) but the UITableView does not until the run time?

You could combine your proposed solutions 1 & 2:

Set the StackView bottom constraint to be “equal” and then if it's empty programmatically change it back to “greater or equal”.

You'll need to update constraints when your data loads to set the value depending on the data received.

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