Search code examples
iosautolayoutuistackview

How to keep UITableView centered on X and Y inside an UIStackView


I have an UILabel and a UITableView inside an vertical UIStackView. I want this stack view to always remain centered, even when elements are added to the table view.

Right now I added a Horizontal in Container and Vertical in Container constraints to the stack view. But it still says that the stack view is missing a Y constraint. If I add one then it won't be centered anymore.

Any idea what constraints should I add to keep it always centered ?

Here are two screen shots with how I want my stack view and one with what I have now:

enter image description here

enter image description here

The second picture I added a vertical space constraint from stack view to title that's why it looks like that.


Solution

  • mmm... I had this very same request from a client some time ago and the thing is that table views are not meant to be used like that because if you add too many items the table is going to grow in both vertical directions and thats not good at all... BUT! as far as I can see, your cells are all the same size so, this is what I did as my table had a few and finite number of rows and all of them were the same size:

    I added a height constraint to the tableView and throw it as an IBOutlet to the class it belongs to. Once you have the number of rows for your tasks, you can just update the constant value for the tableView height constraint you have by multiplying the number of rows for the fixed height of your cells. That way your tableView will have a height defined by the number of rows it contains. You should probably just dump the stack view, use the tableView by itself and add some size and centering constraints to your tableView having into account this height constraint I mentioned... Specifically:

    Leading/Trailing or Width as you prefer, vertically centered inside container and the height constraint you are going to modify on runtime.