简体   繁体   中英

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

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?

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.

NSLayoutAttribute.NotAnAttribute ,

I think here is the problem. You pass in NotAnAttribute

Also,it should be self.addConstraint(constraint)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM