简体   繁体   中英

UILabel inside UITableViewCell - height isn't adjusting correctly

Check out the second UILabel inside of the pink UITableViewCell. As you can see, the text inside it is cut-off. I've been trying to get the height of this UILabel to correctly expand or shrink as a function of how much text is plugged into it - and its not working.

在此处输入图片说明


• I'm using AutoLayouts
• The UILabel is pinned on all 4 sides to the ContentView - which of course is inside the UITableViewCell
• The Cells are all Static cells by the way, not Prototype cells.
• Here's the code I'm using:

(in viewWillAppear)

descriptionLabel.text = " < a bunch of text goes here > "
descriptionLabelSize = descriptionLabel.sizeThatFits(descriptionLabel.bounds.size)
// here's a global var I use to store the height:
descriptionLabelHeight = descriptionLabelSize.height

then, in viewDidAppear (and FYI, I also tried putting the following in will and didLayoutSubviews and in all sorts of other permutations:)

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    var newFrame = descriptionLabel.frame
    newFrame.size.height = descriptionLabelHeight
    descriptionLabel.frame = newFrame

    descriptionLabel.setNeedsLayout()
    view.layoutIfNeeded()
}

Finally, in heightForRowAtIndexPath I use the global var to adjust the TableViewCell's height:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    switch indexPath.row {
    case 0: return 50
    case 1: return descriptionLabelHeight+20   // the + 20 is for padding & margin
    default: return 50
    }
}

The result is mixed: the height of the Label - and the Cell housing it - does adjust - but not enough. It always ends up being too short. And I don't mean that it just cuts off a couple of words, its way too short, cutting off multiple sentences.
But again: the height does adjust. And that's the weird part. Its working - just not enough.

Any tips would be greatly appreciated!

You need to tell table view to dynamically scale the cells based on content:

tableView.rowHeight = UITableViewAutomaticDimension

Then, you can remove your implementation of heightForRowAtIndexPath: - cells should scale automatically. Remember to setup layout constraints correctly though. Without it dynamic sizing won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM