动态设置表格视图单元格行高?

Set tableview cell row height dynamically?

我有一个带有标签和图像的表格视图。在某些单元格中,没有图像,因为我使用 imageView.removeFromSuperview() 将其从单元格中删除。当单元格中有图片时,行高为445,勾选"Custom"。

如何根据标签的长度动态设置行高,而不是在删除图像视图后 long/big 图像视图的大小?

您需要覆盖此方法:

Override func tableview(tableview:UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {}

Return 在此方法中您想要的 indexPath 的所需高度

如果您使用的是 UILabel,它有一个高度为 属性 的框架。

和 heightForRowAtIndexPath,应该涵盖您想要使用的适当方法的内容: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:

不确定您的图片当前是如何设置的,但这里有一个粗略的示例:

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if image != nil {
            return 445.0
        else {
            label.frame.height (or whichever value you'd prefer)
        }
}

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

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

如果你也想 hide/show UIImageView,我必须承认我并不喜欢 removeFromSuperview 方法(因为当单元格被重用时,你有重新添加图像视图,并可能重建其约束)有几个选项:

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

  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
    }
    

    当具有决定单元格高度的竞争约束集时,诀窍是确保它们具有不同的优先级 and/or 它们使用不等式,因此如果两个集都有效,您就不会有无法解决的冲突(例如,图像视图可能具有更高的优先级)。

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