动态设置tableview单元格行高?

joh*_*113 2 xcode uitableview uiimageview tableviewcell swift

我有一个带有标签和图像的tableview.在一些细胞中,没有像我用来imageView.removeFromSuperview()将其从细胞中移除的图像.当单元格中有图像时,行高为445并且"自定义"被检查.

如何根据标签的长度动态设置行高,而不是在删除imageview后imageview的长度/大度?

Rob*_*Rob 8

如果你想要动态行高,你可以定义你的约束(确保它们是明确的),将标签设置numberOfLines为零,然后在viewDidLoad,告诉它行应该自动调整它们的高度:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
Run Code Online (Sandbox Code Playgroud)

如果你想隐藏/显示一个UIImageView,我必须承认我对这种removeFromSuperview方法并不骄傲(因为当重复使用单元格时,你必须重新添加图像视图,并且可能还要重建它的约束)有几种选择:

  1. 对于具有图像视图的单元格,您可以使用不同的单元格原型,而不使用图像视图.然后cellForRowAtIndexPath只需要实例化正确的单元格.

  2. 您可以继续定义一组完整的约束,这些约束对于图像的存在和没有图像都是明确的.然后,您可以activate约束并将图像视图设置hidden为适当的:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomCell
    
        let image = ...  // let's say it was an optional, set if needed, left `nil` if not
    
        cell.customImageView?.image = image
    
        if image == nil {
            cell.customImageView.hidden = true
            cell.imageBottomConstraint.active = false
    
            cell.customLabel.text = ...
        } else {
            cell.customImageView.hidden = false
            cell.imageBottomConstraint.active = true
        }
    
        return cell
    }
    
    Run Code Online (Sandbox Code Playgroud)

    具有决定单元格高度的竞争约束集合的技巧是确保它们具有不同的优先级和/或它们使用不等式,因此如果两个集合都有效,则不会产生不可满足的冲突(例如图像视图可能具有更高的优先级).

  3. 如果需要,您可以"旧学校"并以编程方式确定标签字段的大小,然后实施heightForRowAtIndexPath,但自动布局使此过程变得不必要.