约束冲突,因为我无法停用约束

Constraint conflict because I can't deactivate constraint

我有一个 CollectionView,我想根据内容动态调整它的高度。 我得到一个错误,因为故事板中设置的约束与约束冲突 在我的代码中设置:

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myCollectionView)
    //other constraints of collectionView
    collHeight = myCollectionView.heightAnchor.constraint(equalToConstant: 276)
    collHeight!.isActive = true
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       //other stuff
        collHeight!.constant = collectionView.contentSize.height
        view.layoutIfNeeded()
 }

错误:https://pastebin.com/5yQh5hUP 我无法删除带有 Entf 的约束。 它只将数字设置为 0。我可以通过编程方式停用它吗?

您是否尝试过移除或禁用情节提要限制?

for constraint in self.view.constraints {  
   constraint.isActive = false
}

虽然您可以为约束定义 id 并在循环内检查其值。 其实我不是很清楚你新增的约束条件,但是你可以改变它的常量或者乘数

for constraint in self.view.constraints {
    if constraint.identifier == "xyz" {
        constraint.multiplier = 0.5
    }
}

您有两个选择:

  1. Select 您的冲突约束并检查 "Remove at build time" 选项

  1. 无需在 viewDidLoad 函数中创建约束,您可以创建约束的出口,然后将其设置为常量。

    @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
       super.viewDidLoad()
       view.addSubview(myCollectionView)
       // Set the constant
       collectionViewHeightConstraint.constant = 276 // Change this as you wish
    }