【问题标题】:Constraint conflict because I can't deactivate constraint约束冲突,因为我无法停用约束
【发布时间】:2020-03-24 19:53:47
【问题描述】:

我有一个 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。我可以通过编程方式停用它吗?

【问题讨论】:

  • 您认为这不值得关注吗? “如果您看到不理解的 NSAutoresizingMaskLayoutConstraints,请参阅 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档。”
  • 另外你没有在cellForItemAt 中设置集合视图约束常量,这根本没有意义。

标签: ios swift xcode collectionview


【解决方案1】:

你有两个选择:

  1. 选择您的冲突约束并选中“在构建时删除”选项

  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
    }
    

【讨论】:

  • @Marro 回答您的评论:首先,您应该在 Storyboard 上选择 CollectionViewHeight 约束,这会给您带来麻烦。然后在右侧你会看到它的属性,如果没有,你应该打开 Inspector。在检查器中选择具有标尺图标的“尺寸检查器”。在该选项卡中,您将找到“在构建时删除选项”
【解决方案2】:

您是否尝试过移除情节提要约束或禁用它?

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

虽然您可以为约束定义 id 并在循环内检查其值。 其实我并不完全了解你新添加的约束,但你可以改变它的常数或乘数

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

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2022-12-05
    • 2013-02-16
    • 1970-01-01
    • 2018-03-29
    • 2021-08-04
    相关资源
    最近更新 更多