Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give dynamic height to labels contained within a UIStackView?

Inside a UITableView cell I have the following structure.

screenshot of UITableView structure

It has two UIStackView instances, Left and Right

  1. Left stack view contains 3 views. Each view containing 1 label (Label1, Label2, Label3)
  2. Right stack view contains 2 views. Each view containing 1 label (Label5, Label6)

Constraints for Label1, Label2 and Label3 are Top, Left, Right and Bottom with respect to its parent views.

Now when I add text to Label1, Label2 and Label3 at runtime it gives dynamic height but leaves space in top and bottom, for those label having less text. Below is the output.

screenshot of cell dynamic height issue

I want to reduce the top and bottom spaces for all the three labels i.e Label1, Label2, Label3.

Any help will be appreciated.

like image 956
user7420795 Avatar asked Oct 22 '25 01:10

user7420795


2 Answers

I think You have use distribution of Stack view as fill equally so it gives equal space to each one. I think for this you have to use fill proportionally. this will adjust height accordingly

Choose fill proportionally from here

if this not working then choose fill proportionally and give height to each label it will adjust.

Check how to give height to labels . enter image description here

after giving each label height inside stack view like this . your it will adjust itself according to data.Like this

enter image description here

like image 154
Amit gupta Avatar answered Oct 25 '25 01:10

Amit gupta


For dynamic height use self sizing cells in tableview. Set rowHeight and estimatedHeight properties for tableView

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100

Set the stackview distribution property to .fillproportionally

as per the UIStackView documentation of .fillproportionally property

A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.

in code:

stackView.distribution = fillproportionally

or in storyboard

enter image description here

like image 22
Suhit Patil Avatar answered Oct 25 '25 01:10

Suhit Patil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!