ios - 具有自动布局和 UITableAutomaticDimension 的动态高度表单元格(动态 UILabel + 几个 UIImageViews)

标签 ios objective-c iphone uitableview autolayout

我看了三天有关动态表格单元格和自动布局的文章,但到目前为止还没有工作。

下面是我想要的表格单元格。这里的主要问题是用于帖子文本和 UIImages 的 UILabel。

enter image description here

这是 UI 元素的层次结构。

- Content View
    + ...
    + UILabel for text - dynamic height
    + UIView - image view container
        * UIImageView
        * UIImageView
        * ....

标签的换行模式将文本换行且行数设置为 0。 标签和容器 View 对顶部、底部、前导和尾随有约束。 ImageViews 是在运行时添加的,并且具有顶部、前导、尾随、底部和高度约束的约束。 第一个 ImageView 对容器 View 具有顶部约束,最后一个 ImageView 对容器 View 具有底部约束,其他 ImageView 对上部 ImageView 具有顶部约束。

enter image description here

首次加载表格时(单元格具有不同的图像计数),它看起来不错,但是当我上下滚动时,某些单元格中的约束被破坏,并且图像在单元格内重叠。

这是错误输出:

Unable to simultaneously satisfy constraints.   Probably at least one of the constraints in the following list is one you don't want.      
Try this:       
(1) look at each constraint and try to figure out which you don't expect;       
(2) find the code that added the unwanted constraint or constraints and fix it.

"<NSLayoutConstraint:0x17428aaf0 V:|-(0)-[UIImageView:0x14be77ed0]   (active, names: '|':UIView:0x14be75b20 )>",
"<NSLayoutConstraint:0x17428a6e0 UIImageView:0x14be77ed0.height == 160   (active)>",
"<NSLayoutConstraint:0x17428acd0 UIImageView:0x14be77ed0.bottom == UIView:0x14be75b20.bottom   (active)>",
"<NSLayoutConstraint:0x174289650 V:|-(0)-[UIImageView:0x14be43ce0]   (active, names: '|':UIView:0x14be75b20 )>",
"<NSLayoutConstraint:0x17428bb80 UIImageView:0x14be43ce0.height == 160   (active)>",
"<NSLayoutConstraint:0x17428be50 V:[UIImageView:0x14be43ce0]-(10)-[UIImageView:0x14be74b10]   (active)>",

"<NSLayoutConstraint:0x17428bfe0 UIImageView:0x14be74b10.height == 160   (active)>",
"<NSLayoutConstraint:0x17428c080 UIImageView:0x14be74b10.bottom == UIView:0x14be75b20.bottom   (active)>"

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x17428be50 V:[UIImageView:0x14be43ce0]-(10)-[UIImageView:0x14be74b10]   (active)>

请帮我解决这个问题。谢谢。

最佳答案

要确保堆栈 View 在单元格出列时不包含旧图像,您需要在 prepareForReuse() 中清理它:

override func prepareForReuse() {
    super.prepareForReuse()

    stack.arrangedSubviews.forEach {
        stack.removeArrangedSubview($0)
        $0.removeFromSuperview()
    }
}

关于ios - 具有自动布局和 UITableAutomaticDimension 的动态高度表单元格(动态 UILabel + 几个 UIImageViews),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42222339/

相关文章:

iphone - 无法识别的选择器发送到类 0x51e8'

ios - 如何在 iOS Swift 3 中将 JSON 字符串转换为字典数组

iphone 5 Default-568h@2x.png 图像在模拟器上有效,但在实际设备上无效

android - 我可以通过 WIFI-Direct 在 Android 和 IOS 之间连接吗?

objective-c - UITEXTVIEW:获取最近在uitextview中输入的单词

ios - 单击自定义 UITableViewCell 上的按钮会抛出 EXC_BAD_ACCESS

ios - Objective-C 检查带整数的数组是否包含整数

iphone - 设置 UIVIew 的背景颜色

ios - 双segue tableView?

ios - 动画后更改 ViewController