Swift iOS tableView static cell动态计算高度

TableView是iOS开发中经常使用的组件。有些表格由于UILabel包括的文本字数不一样,须要显示的高度也会不同,因此须要动态计算static cell的高度。我用的是static cell,注意每行的高度都须要指定,默认样式的cell高度是44,第三行(row == 2)进行了动态计算。第四行须要依据是否有内容推断是否显示,没有则返回高度0。

依据实际尝试和查看国外文章。发现

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) 对于静态表格好像没有作用。也有可能是我没有弄清楚正确使用方法。


  override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 2 {
            return heightForView(task.summary!, font: UIFont(name: "Helvetica", size: 15.0)!,  340) + 30
        } else if indexPath.row == 3 {
            if task.type == TaskType.TYPE_PLAN.rawValue {
                if let descr = task.descr {
                    return heightForView(descr, font: UIFont(name: "Helvetica", size: 15.0)!,  340) + 30
                }
            } else {
                return 0
            }
        } else if indexPath.row == 4 {
            return 110
        }
        
        return 44
    }

    // 计算高度
    func heightForView(text:String, font:UIFont, CGFloat) -> CGFloat{
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text
        
        label.sizeToFit()
        return label.frame.height
    }


原文地址:https://www.cnblogs.com/llguanli/p/7132225.html