user7420795
user7420795

Reputation: 199

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.

Upvotes: 4

Views: 11734

Answers (3)

Amit gupta
Amit gupta

Reputation: 553

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

Upvotes: 5

Rahul Jamba
Rahul Jamba

Reputation: 11

Firstly go to main UIStackview height constraint edit option and set constant height greater than current constant height. After that you will set the label line number 0.

Now add tablewView row height delegate function and return UITableView.Autodemenssion height.

enter image description here

Upvotes: 0

Suhit Patil
Suhit Patil

Reputation: 12023

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

Upvotes: 2

Related Questions