user4216977
user4216977

Reputation:

tableView not setting automatic row height

In my project, I have a static tableView with 3 sections. The cell in the second section holds a label that is filled dynamically and therefore has a dynamic height. The cell should adjust its height to the label's height. Here's what I tried, without success:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.section == 0 {
      return 44
    } else if indexPath.section == 1 {
      return UITableViewAutomaticDimension
    } else if indexPath.section == 2 {
      return 80
    } else {
      return 50
    }
}

The heights of all sections are set properly except the automatic dimensions. Any help?

Upvotes: 0

Views: 659

Answers (2)

Harshal Bhavsar
Harshal Bhavsar

Reputation: 1673

set this line in viewDidLoad()

tableView.rowHeight = UITableViewAutomaticDimension

then write this table view method

 func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return UITableViewAutomaticDimension
    }

also make sure you have used the auto layout properly. and you have set the number of lines for lable = 0

Upvotes: 2

Alessandro Orrù
Alessandro Orrù

Reputation: 3513

You also need to provide an estimated row height. You can do that by using the estimatedRowHeight property of your UITableView, or implementing the corresponding delegate method:

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return XXXXX // Provide your estimation here, or pass UITableViewAutomaticDimension (not the best for performances)
}

Reference: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html

Upvotes: 0

Related Questions