Codetard
Codetard

Reputation: 2595

UITableViewCell Auto Sizing Issue Swift

This is the custom UITableViewCell I've designed In a xib. The selected element is a UILabel, which is required to be expand with respect to amount of text. In storyboard cell each element has a constant height with spacing.

enter image description here

Here's the code that I have in a UITableViewController:

class TableViewController: UITableViewController {
private var exampleContent = ["This is a short text.", "This is another text, and it is a little bit longer.", "Wow, this text is really very very long! I hope it can be read completely! Luckily, we are using automatic row height!, Wow, this text is really very very long! I hope it can be read completely! Luckily, we are using automatic row height!"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.estimatedRowHeight = 224.0
    tableView.rowHeight = UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("DescriptionOnlyCell", owner: self, options: nil)?.first as! DescriptionOnlyCell
    cell.label.numberOfLines = 0
    cell.label.text = exampleContent[indexPath.row]
    return cell
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return exampleContent.count
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

Output of the code is same exactly as the storyboard cell, no dynamic resizing.

I've read a few threads on stackover and most of them explains same like the code posted above. Though I suspect there's some issue with the storyboard constraints. Any hint would be really helpful.

Upvotes: 0

Views: 57

Answers (3)

Liubo
Liubo

Reputation: 702

Instead of setting the constant height values for your labels, set the top and the bottom spacing constraints for all elements and remove height constraints or set their priority lower.

Upvotes: 2

Anvesh Tokala
Anvesh Tokala

Reputation: 431

I hope this would fix your resizing.

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableView.layoutIfNeeded()

}

Upvotes: 0

Nitish
Nitish

Reputation: 14123

Do the following for the selected label :

  1. Set number of lines = 0
  2. Set lineBreak mode = WordWrap
  3. Set height constraint to >= 15

I am relying on the info you shared that vertical spacing for all UI components is set.

Upvotes: 0

Related Questions