JsW
JsW

Reputation: 1758

How to calculate the height of a UILabel?

I'm trying to set the UITableViewCell's Height depending on the height of a UILabel.
My problem is similar to this one.
But the OC code in that answer seems to been deprecated now(I'm not sure, just can't find it).
I'm using the following code to calculate the height of the label.

extension String {
    // the length of text in one line
    func size(ofFont font: UIFont) {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
}

In cellForRow: method:

let size = text.size(ofFont: font)
let height = ceil(size.width/(UIScreen.main.bounds.width))*size.height

But it would be additional break line if the last word is too long to display in one line.
So, here comes the bug.
Thank you for any suggestion.

Upvotes: 0

Views: 560

Answers (2)

Berlin
Berlin

Reputation: 2227

In Swift 3

set BackgroundView Constraint like leading, trailing,top,bottom, please show image.

enter image description here

set UILabel Constraint like leading, trailing, top, bottom

and set it's property numberOfLines = 0

enter image description here

and after that your viewController class ViewDidLoad method write this code.

override func viewDidLoad() {
        super.viewDidLoad()
        //dynamic tablview
        yourTablview.estimatedRowHeight = 83.0
        yourTablview.rowHeight = UITableViewAutomaticDimension
    }

I hope it's work for you.

Upvotes: 3

Phyber
Phyber

Reputation: 1368

You should use UITableViewAutomaticDimension

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

And you should also set numberOfLines

cell.label.numberOfLines = 0

Don't forget to set constraints on all sides

Upvotes: 3

Related Questions