【问题标题】:Changing the height of a dynamic-height UITableViewCell after it's already appeared在动态高度 UITableViewCell 出现后更改其高度
【发布时间】:2016-02-01 23:45:57
【问题描述】:

我跟着this tutorial创建了一个动态高度的UITableViewCell。

我的原型单元格有 1 个标签(非常简单)。该标签将单元格边缘的所有边的约束设置为“0”。该标签具有numberOfLines = 0 并包含单词。

在我的 UITableView 设置中,我这样做:

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

基本上,一切正常。每个单元格都有自己不同的高度。

当我用不同的文本更新该标签时,问题就出现了。单元格的高度保持不变,文本被截断或出现空白。

有没有办法告诉单元格“重绘”自己,以便再次计算高度?

理想情况下,我希望 UITableViewCell 类中执行此操作,因为它会在此接收更新标签文本的通知。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您必须实现 estimatedHeightForRowAtIndexPath 并计算标签的大小。

    例如:

    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
    } 
    

    【讨论】:

    • 我怎么称呼它? (当我的单元格收到通知中心消息时,它需要调用一些东西来“调整”自己的高度)
    • 只需实现上面提到的方法并调用tableView.reloadData()
    • 我可以只重新加载单元格而不是整个表格吗?
    • 是的,您应该在tableView.beginUpdates()tableView.endUpdates() 之间致电tableView. reloadRowsAtIndexPaths([indexPath], withRowAnimation ...)
    • 为什么是被接受的答案?这需要将代码添加到 UITableViewController 类中,而不是单元格本身。这也是一个非常简单的示例,其中只有文本 - 如果您有一个更复杂的单元格怎么办?
    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2013-06-15
    • 2019-10-12
    • 2017-05-21
    • 1970-01-01
    相关资源
    最近更新 更多