我有一个带有标签和图像的表格 View 。在某些单元格中,没有图像,因为我使用 imageView.removeFromSuperview()
将其从单元格中删除。当单元格中有图片时,行高为445,“自定义”勾选。
如何在删除 ImageView 后根据标签的长度而不是 ImageView 的长度/大小动态设置行高?
最佳答案
如果你想要动态行高,你可以定义你的约束(确保它们是明确的),将标签的 numberOfLines
设置为零,然后在 viewDidLoad
中,告诉它行应该自动调整它们的高度:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
如果你也想隐藏/显示 UIImageView
,我必须承认我对 removeFromSuperview
方法并不着迷(因为当单元格被重用时,你必须重新添加 ImageView ,并且可能还要重建它的约束)有几个选项:
对于带有 ImageView 的单元格和不带有 ImageView 的单元格,您可以使用不同的单元格原型(prototype)。然后
cellForRowAtIndexPath
只需要实例化正确的单元格。您可以继续定义一整套约束,这些约束对于图像的存在和不存在都是明确的。然后,您可以
激活
约束并根据需要将 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 可能具有更高的优先级)。
如果您愿意,您可以“老派”并以编程方式确定标签字段的大小,然后实现
heightForRowAtIndexPath
,但自动布局使此过程变得不必要。
关于xcode - 动态设置表格 View 单元格行高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37890804/