在 tableview 单元格中更改 UIImageView display/dimensions

Change UIImageView display/dimensions within a tableview cell

我想根据图像 link 是否可用于该单元格行来隐藏特定单元格的 UITableview 单元格中的 UIImageView。

如果无法从后端获取某个单元格的图像 url,那么我想 "disable" UIImageview 并回收其 space 以便标签展开。 (UILabel 放在左边,UIImageView 放在右角。 因此,如果没有图像,那么我希望标签文本在有更多文本时向右扩展。)

我尝试了两种解决方案: 1.通过设置宽度约束将UIImageView的宽度更改为0。

let widthConstraint = NSLayoutConstraint(item: cell.articleImageView as UIView,
                            attribute: NSLayoutAttribute.Width,
                            relatedBy: .Equal,
                            toItem: nil,
                            attribute: NSLayoutAttribute.NotAnAttribute,
                            multiplier: 0,
                            constant: 0)
 cell.myImageView.addConstraint(widthConstraint) 

2。从单元格中删除图像视图。

cell.myImageView.removeFromSuperView() 

但是当我滚动浏览和返回时,其他单元格的图像也受到影响并被隐藏。同样 myImageView.hidden = true.

顺便说一句,我使用 tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) 来检索单元格。表格视图和单元格是在情节提要中创建的。

任何帮助如何回收 space 单元格中隐藏的 UIImageview 占用的空间,但在滚动时不影响其他行?

不要以编程方式添加约束,而是在 Interface Builder 中分配宽度并在代码中为宽度约束创建出口。然后,在您的单元格出列之后,如果您希望隐藏它,您可以将宽度约束的 constant 属性 更改为 0,或者更改为您希望其扩展宽度的任何值。

编辑:此外,我按照@MuhammadZohaibEhsan 在下面评论中的建议,在单元格的 prepareForReuse() 方法中将约束的 constant 属性 重置为原始大小。