Reputation: 6560
I am writing a table view where each cell shows an image and some texts. These texts are downloaded via Internet, just like a news app, the texts are dynamic.
There can be up to 2 lines for the texts and the font size is fixed. (The font size can be changed via a setting page though)
I am using fixed height for table cells and I need to calculate the UILabel height at run time for layout arrangement.
How do I calculate the UILabel height with a fixed font size (say 20) and 2 lines allowed?
Upvotes: 0
Views: 798
Reputation: 391
Try setting number of lines to 2 then call sizeToFit()
on your UILabel.
After that, get your label height through its frame - label.frame.size.height
Upvotes: 1
Reputation: 106
If I am not wrong, you want to set your tablecell's or UILabel's height dynamically according to text length.
An easier way is to set up the UILabel autolayout to tablecell in your interface builder, and set the UILabel number of lines to zero, then put the following in your tableView's viewDidLoad:
tableView.estimatedRowHeight = 44.0 //(or some number you prefer)
tableView.rowHeight = UITableViewAutomaticDimension
This way, you can have as many lines as you like without having to calculate the label's dimensions.
Upvotes: 1