xcode - 动态设置表格 View 单元格行高?

标签 xcode swift uitableview uiimageview tableviewcell

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

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

最佳答案

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

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

如果你也想隐藏/显示 UIImageView,我必须承认我对 removeFromSuperview 方法并不着迷(因为当单元格被重用时,你必须重新添加 ImageView ,并且可能还要重建它的约束)有几个选项:

  1. 对于带有 ImageView 的单元格和不带有 ImageView 的单元格,您可以使用不同的单元格原型(prototype)。然后 cellForRowAtIndexPath 只需要实例化正确的单元格。

  2. 您可以继续定义一整套约束,这些约束对于图像的存在和不存在都是明确的。然后,您可以激活约束并根据需要将 ImageView 设置为隐藏:

    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
    }
    

    当具有决定单元格高度的竞争约束集时,诀窍是确保它们具有不同的优先级和/或它们使用不等式,因此如果两组都有效,您就不会遇到无法满足的冲突(例如, ImageView 可能具有更高的优先级)。

  3. 如果您愿意,您可以“老派”并以编程方式确定标签字段的大小,然后实现 heightForRowAtIndexPath,但自动布局使此过程变得不必要。

关于xcode - 动态设置表格 View 单元格行高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37890804/

相关文章:

ios - 监听蓝牙外设按钮事件 iOS Swift

swift - 更新位置时 MKmapview 会重置

ios - UITableView 高度等于 contentSize 高度

iphone - 自定义单元格的 UITableView 错误 "Could not load NIB in bundle:"

objective-c - 解决 id 类型的 "No known instance method for selector"错误

xcode - 使用 WatchKit (Watch) 的基于页面的界面中的页码?

swift - 创建初始值为 0 的信号量会导致执行出现问题

ios - 从 viewForHeaderInSection 中的 UIButton 获取数据发送到 add Target 中的方法

ios - UITableViewCell 可重用性问题。修改一个细胞会影响其他细胞

ios - 输入所有代码后,Xcode 完全跳过 firebase 登录?