Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27113

Dynamic table view height

enter image description here

The idea is to resize height of the cell automatically based on few controls heights. As you can see on image above I have Top Label and Bottom Label. These two labels can have different height based on text length.

Few words about setup in storyboard.

I set number of lines to 0 for 2 described labels to allow grow their height dynamically based on given text.

For the Top Label I have next constraints:

enter image description here

For the Bottom Label I have next constraints:

enter image description here

So I we say about vertical spacing between 1000 green label and bottom label it's every time the same:

enter image description here

But without this spacing cell won't stretch height. How can I reduce this vertical spacing? Because there is to much spacing between "1000 green label" and bottom label in case if top label have big height because of text.

In -viewDidLoad method I set:

[self.theTableView setEstimatedRowHeight:145];
[self.theTableView setRowHeight:UITableViewAutomaticDimension];

Seems it works pretty cool sometimes with a bug described here but I don't know how to restrict that vertical spacing:

http://www.appcoda.com/self-sizing-cells/

Upvotes: 0

Views: 620

Answers (1)

user4151918
user4151918

Reputation:

Set the bottom label's top constraint to be >= 11.5 (or whatever its minimum spacing should be).

This will let the cell adjust that vertical spacing, depending on the other content in the cell.

Update:

In iOS 9, this would much more simply be handled by UIStackView.

A horizontal stack view would constrain (and determine the cell height based on the) two inner vertical stack views. The left vertical stack would handle the image, banner, and label layout, and the right vertical stack would handle the top label, 10000, and bottom label layout. You'd only need with 4 constraints (for the horizontal stackView to constrain it to the contentView).

Upvotes: 1

Related Questions