Corvette King
Corvette King

Reputation: 21

Expression type 'NSLayoutConstraint' is ambiguous without more context

I'm receiving the following error when I try to make a build of my iOS app. How can I find out what is causing it?

Error: Expression type 'NSLayoutConstraint' is ambiguous without more context

Code:

private func centerIndicator() {
    let xCenterConstraint = NSLayoutConstraint(
        item: loadingView ?? default value, attribute: .centerX, relatedBy: .equal,
      toItem: indicator, attribute: .centerX, multiplier: 1, constant: 0
    )
    loadingView.addConstraint(xCenterConstraint)

    let yCenterConstraint = NSLayoutConstraint(
      item: loadingView, attribute: .centerY, relatedBy: .equal,
      toItem: indicator, attribute: .centerY, multiplier: 1, constant: 0
    )
    loadingView.addConstraint(yCenterConstraint)
  }

Upvotes: 0

Views: 405

Answers (1)

Procrastin8
Procrastin8

Reputation: 4503

Your most likely culprit is default value, it shouldn't be there. If loadingView is non-optional you can just delete ?? default value. If it is optional, then you should probably be wrapping this in an if let loadingView = loadingView block. Setting constraints on random views will not work out.

Next, Apple doesn't suggest adding constraints to views directly anymore. Instead, use the isActive property.

NSLayoutConstraint(
      item: loadingView, attribute: .centerY, relatedBy: .equal,
      toItem: indicator, attribute: .centerY, multiplier: 1, constant: 0
).isActive = true

But these are pretty simple constraints. An even better way is to use layout anchors instead.

loadingView.centerYAnchor.constraint(equalTo: indicator.centerYAnchor).isActive = true

Upvotes: 1

Related Questions