Swift dynamic table cell height [duplicate]
Asked Answered
P

2

43

I have tableview with prototype cell, in the cell I have imageview and some text under. The text label is one laine in the prototype cell, but sometimes it is more than one line, I'm loading the data to the table view after server call. The label in storyboard Lines are set to 0 and Line Break to Word Wrap. I also tried http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

but no effect. If I use Using Auto Layout in UITableView for dynamic cell layouts & variable row heights everything works because the label text is predefined, but I'm loading the data from server and I reload the tableView after the API call, and then the label is just one line.

Pica answered 12/4, 2016 at 12:58 Comment(7)
Does your label have bottom constraint to tableViewCell?Clavier
yes, I use suggested constraints, should I remove it?Pica
see #36438361Correct
it is not duplicate, because this works if I have the data, but I'm loading the data after the tableview was created and then call reloadData()Pica
No don't remove it...Try following the answer to the link suggested by @CorrectClavier
Can you share the screenshot and code or if possible share the projectClavier
The problem was in My constraints, cleared them all and added them manually, and in viewDidLoad used self.tableView.setNeedsLayout() self.tableView.layoutIfNeeded()Pica
N
55

You should use UITableViewAutomaticDimension provides a solution for displaying dynamic content.

Use below code in viewDidLoad:

tableView.estimatedRowHeight = YourTableViewCellHeight
tableView.rowHeight = UITableView.automaticDimension

Read more from here

Hope it helps. :)

Naoise answered 12/4, 2016 at 13:10 Comment(2)
This works with autolayout! I add also that "tableView.estimatedRowHeight = xxx " is needed in order to make it work, it's not optional.Rigorous
raywenderlich.com/1067-self-sizing-table-view-cellsMuskrat
B
26

make sure UILabel height constraint not to be constant, if constant it have to set Relation greater than or equal to from attribute inspector

make sure UITableViewestimate row height set as per your.

   tableView.estimatedRowHeight = 85

and write in UITableViewCell class

 cell.lbl_name.sizeToFit()
 cell.lbl_name.numberOfLines = 0

Make sure your UITableViewDelegate method

func tableView(tableView: UITableView,
    heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
Barbary answered 12/4, 2016 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.