SnapKit更新约束会导致冲突

时间:2018-11-25 17:50:38

标签: ios swift autolayout uikit snapkit

我正在针对iOS 12 SDK,Swift 4和SnapKit 4.2构建iOS应用

我想在点击按钮时更新约束,但它与约束的先前版本产生冲突。

这是我的代码:

private var menuConstraint: Constraint?

override func updateViewConstraints() {
    super.updateViewConstraints()

    menuVc.view.snp.makeConstraints { (make) in
        self.menuConstraint = make.top.equalTo(view.snp.top).constraint
        make.right.equalTo(view.snp.right)

        make.width.equalTo(100)
        make.height.equalTo(100)
    }
}

@objc func onMenuTap() {
    self.menuConstraint!.update(offset: 100)
}

调用onMenuTap时出现以下错误:

[LayoutConstraints] 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. 
(
"<SnapKit.LayoutConstraint:0xABC@MyViewController.swift#77 UIView:0xDEF.top == UIView:0xGHI.top>",
"<SnapKit.LayoutConstraint:0xABC@MyViewController.swift#77 UIView:0xDEF.top == UIView:0xGHI.top + 100.0>"
)

您可以看到top约束的先前版本(不带偏移)与新版本冲突。好像它没有更新现有约束,而是只是创建了一个新约束。

我尝试了几种变体:

  • 将更新行换成snp.updateConstraints结束符
  • 在首次创建约束时设置初始偏移量
  • 抓取基础LayoutConstraint并直接更新constant

我总是收到相同的错误消息。

我的配置有误吗?

1 个答案:

答案 0 :(得分:1)

请勿在{{1​​}}内放置约束,因为它会多次创建约束,因此请在updateViewConstraints内设置代码