Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: Unknown layout attribute'

Tags:

ios

swift

Im trying to add a constraint programmatically to a button inside a UIView:

let constraint = NSLayoutConstraint(item: arrowButton, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, 
                 toItem: self, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 10)
arrowButton.addConstraint(constraint)

I want the leading margin of the button to be 10 from the left margin of the view. This code is run inside the view so self is the view. The code above is giving the error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:]: Unknown layout attribute'

What am I doing wrong?

like image 531
Deekor Avatar asked Jan 17 '26 06:01

Deekor


1 Answers

NSLayoutAttributeNotAnAttribute:

A placeholder value that is used to indicate that the constraint’s second item and second attribute are not used in any calculations. Use this value when creating a constraint that assigns a constant to an attribute. For example, item1.height >= 40. If a constraint only has one item, set the second item to nil, and set the second attribute to NSLayoutAttributeNotAnAttribute.

You are having two items: arrowButton and self, but you specify NSLayoutAttributeNotAnAttribute saying I just need one item. That's why it is failed.

I suggest you use storybard or xib to practice the auto layout first by feeling how it works, and then start coding it. You clearly misunderstand auto layout. If you are defining two view's layout relation, then NSLayoutAttributeNotAnAttribute will never be valid to use.

like image 98
Wingzero Avatar answered Jan 19 '26 18:01

Wingzero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!