David van Dugteren
David van Dugteren

Reputation: 4109

Constraint must contain a first layout item NSLayoutConstraint

I had my LayoutConstraints working fine, then all of a sudden I started getting this when adding Constraints to my view.

    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Constraint must contain a first layout item'
*** First throw call stack:
(0x7cd012 0x2017e7e 0x7ccdeb 0xde6bf1 0x9c487 0x994a3 0x414fb 0x20224 0x5c6c0 0xc30e83 0x78c376 0x78be06 0x773a82 0x772f44 0x772e1b 0x28eb7e3 0x28eb668 0x149465c 0x2cfd 0x2c25)
libc++abi.dylib: terminate called throwing an exception

And there exists no immediate documentation on the internet or on the Apple Docs as to what the error message means.

Just wondering if anyone has encountered this error, and know what I can do to troubleshoot it?

Upvotes: 16

Views: 16283

Answers (5)

Zee
Zee

Reputation: 1697

This happened when I accidentally deleted the 'referencing outlet' for one of my UI elements.

Upvotes: 0

SmileBot
SmileBot

Reputation: 19642

If you're hanging on to your views with properties make sure they're strong! This could account for them being nil.

Upvotes: 8

codeburn
codeburn

Reputation: 2004

This can also happen if you switch off Autolayout for some reason, but you're still adding constraints to any subview via code (e.g. for handling orientation changes)

This happened to me when I used to different NIB's for the iPhone and iPad and switched off Autolayout for only the iPhone NIB while using a common .m file.

Solution is to check for the device type and skip the layout addition where it's not needed.

Upvotes: 0

Pravara Patil
Pravara Patil

Reputation: 513

One more reason for this error/crash can be, the views passed to the [NSLayoutContraint constraintWithItem ...] method are nil.

Upvotes: 34

David van Dugteren
David van Dugteren

Reputation: 4109

Ah, found the issue. For anyone who has this issue, it's because the view hasn't been created in the nib/UIView yet, so no constraints can apply.

I moved the Constraint code from the initWithNib method to viewDidLoad and the error naturally stopped occurring.

Upvotes: 24

Related Questions