WeCan
WeCan

Reputation: 597

Swift 4.0 cannot invoke initializer for type 'NSLayoutConstraint' with an argument list of type '(NSLayoutConstraint)'

I am using XCode Version 9.0 (9A235), macOS Sierra Version 10.12.6 (16G29), iOS 11.0.

I need to add constraint into array and then later I need to activate it.

For doing this I did like...

// 1.Declare and initialized  the constraint

private lazy var labelConstraints = [NSLayoutConstraint]()

// 2.Prepare constraint   
let widthConstraint = 
    headerLabel.widthAnchor.constraint(equalTo: licenseLabel.widthAnchor)

// 3.Constraint added into the array   
labelConstraints.append(NSLayoutConstraint(widthConstraint))

// 4.Finally activate the constraints   
labelConstraints.activate()

After build my xcode project it throws an error like

ERROR: **cannot invoke initializer for type 'NSLayoutConstraint' with an argument list of type '(NSLayoutConstraint)'** 

**labelConstraints.append(NSLayoutConstraint(widthConstraint))**

Upvotes: 0

Views: 840

Answers (1)

rob mayoff
rob mayoff

Reputation: 385610

Your first problem is here:

labelConstraints.append(NSLayoutConstraint(widthConstraint))

Your widthConstraint variable is already an NSLayoutConstraint, so you don't need to try to convert it to an NSLayoutConstraint. Just do this:

labelConstraints.append(widthConstraint)

Your second problem is here:

labelConstraints.activate()

Type Array doesn't have an activate method. You can activate all constraints in labelConstraints like this:

NSLayoutConstraint.activate(labelConstraints)

Upvotes: 1

Related Questions