0

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.

JsW
  • 1,682
  • 3
  • 22
  • 34

2 Answers2

3

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

Phyber
  • 1,368
  • 11
  • 25
  • Thank you, `UITableViewAutomaticDimension ` is all I need. – JsW Aug 04 '17 at 02:13
  • I got a new problem and need your help. The height of the collection view will be 0 if I set UITableViewAutomaticDimension. The collection view works well if I set a fixed height to the cell. The collection view is initialed from the storyboard and setup in customized TableViewCell. Thank you. – JsW Aug 04 '17 at 13:37
  • @CallOfOrange Let's solve that problem in [the chat](https://chat.stackoverflow.com/rooms/151072/phyber-and-calloforange) – Phyber Aug 04 '17 at 13:44
3

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.

Berlin
  • 2,115
  • 2
  • 16
  • 28
  • My answer is helpful then please give upvote and Right – Berlin Aug 03 '17 at 16:00
  • Thank you, I already set the constraints to the label. `UITableViewAutomaticDimension ` is all I need. Thank you again for your detailed answer. – JsW Aug 04 '17 at 02:15
  • I got new a problem and need your help. The height of the collection view will be 0 if I set UITableViewAutomaticDimension. The collection view works well if I set a fixed height to the cell. The collection view is initialed from the storyboard and setup in customized TableViewCell. – JsW Aug 04 '17 at 13:36