Changing the height of a dynamic-height UITableViewCell after it's already appeared

微笑、不失礼 提交于 2020-01-06 20:14:38

问题


I followed this tutorial to create a dynamic height UITableViewCell.

My prototype cell has 1 label (pretty simple). That label has constraints set to "0" for all sides of the cell edges. That label has numberOfLines = 0 and wraps the word.

In my UITableView setup, I do this:

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 100.0 //some random number 

Basically, everything works. Each cell has its own different height.

The problem arises when I update that label with different text. The height of the cell stays the same, and the text just gets truncated OR white space appears.

Is there a way to tell the cell to "redraw" itself so that it calculates the height again?

Ideally, I'd like to do this inside the UITableViewCell class, since that's where it receives a notification to update the label text.


回答1:


You have to implements estimatedHeightForRowAtIndexPath and calculate your label's size.

for example :

override func tableView(tableView: UITableView,
                        estimatedHeightForRowAtIndexPath 
                        indexPath: NSIndexPath) -> CGFloat {
   let model = YourModelArray[indexPath.row]
   // Label fontName and size
   let attributes = [
            NSFontAttributeName : UIFont(name: "FontName-Regular", size: 16) as! AnyObject]
    let nsStringText = model.text as! NSString
    // Calculate the size here 
    //--------------------//
    //--10--UILabel--10--//
    //-----Element------//
    //------------------//
    let size = nsStringText.
                  boundingRectWithSize(CGSize(width: self.tableView.frame.width - 20,
                  height: 1000), 
                  options:[NSStringDrawingOptions.UsesLineFragmentOrigin,
                           NSStringDrawingOptions.UsesFontLeading],
                           attributes: attributes, context: nil)
    // Basically add other elements heights and vertical Spacing between them
    return size.height + element.frame.height + verticalSpacingBetweenLabelAndElement
} 


来源:https://stackoverflow.com/questions/35142584/changing-the-height-of-a-dynamic-height-uitableviewcell-after-its-already-appea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!