自动版式ImageView高度锚在收藏夹视图中发生冲突并且无法正常工作

时间:2019-06-28 16:43:50

标签: swift uicollectionview autolayout imageview uicollectionviewcell

我遇到这个问题,因为我在集合视图单元格中拥有此图像视图,并且在cellForRow配置功能中,我根据模型对象是否包含图像来设置图像视图的高度锚点。如果包含图像,则高度为200,否则为1。现在,我收到此错误。

该错误似乎最初可以解决约束,并且在第一次加载集合视图时,我能够正确查看单元格。只有当我重新加载collectionview时,我才遇到未显示imageview的单元格问题,或者imageview的高度是1,应该是200。因此,“ 1”的高度锚点的优先级高于200。

  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:0x600001643d40 UIView:0x7fd7fdea2ac0.height == 200   (active)>",
        "<NSLayoutConstraint:0x60000165eb70 UIView:0x7fd7fdea2ac0.height == 1   (active)>"
    )

我已经更改了优先级,但这似乎也不起作用:

   if post.postMedia.isEmpty {
            cell.postMedia.heightAnchor.constraint(equalToConstant: 1).isActive = true
            cell.postMedia.heightAnchor.constraint(equalToConstant: 1).priority = UILayoutPriority(rawValue: 999)
        }else {
            cell.postMedia.heightAnchor.constraint(equalToConstant: 200).isActive = true
            cell.postMedia.heightAnchor.constraint(equalToConstant: 200).priority = UILayoutPriority(rawValue: 1000)
        }

postMedia is the array that contains images. If it is empty the height anchor is 1 and priority is set to 999. and 200 one is given 1000. But that still doesn't work. Is there anything else I can do when two constraints are conflicting one another? 

请多多帮助。

1 个答案:

答案 0 :(得分:0)

我认为您在每次加载单元格时都会添加新的约束。单元被重用,因此对于图像高度会遇到多个冲突约束。您应该在单元格中保留对高度限制的引用,并在加载单元格时更新其常数。

您可以将该属性设为可选:

var heightConstraint: NSLayoutContraint?

并在加载单元格时创建一个nil(如果它是heightConstraint.constant = 200),否则只需更新1(或let height: CGFloat = post.postMedia.isEmpty ? 1 : 200 if cell.heightConstraint == nil { cell.heightConstraint = cell.postMedia.heightAnchor.constraint(equalToConstant: height) cell.heightConstraint?.isActive = true } else { cell.heightConstraint.constant = height } )。

{{1}}