How do I add this constraint in Xcode? It seems my

2019-08-22 17:12发布

问题:

My code is below, as well as the image of my app. Basically I want to add a constraint in the viewDidLoad method for this view controller to align the two labels so they start at the same x position. For whatever reason, I'm getting this warning, though:

Incompatible pointer to integer conversion sending 'UIView *' to parameter of type 'NSLayoutRelation' (aka 'enum NSLayoutRelation');

And when I run the app I get the following error:

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

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.carMakeLabel attribute:NSLayoutRelationEqual relatedBy:self.view toItem:self.carModelLabel attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];

[self.view addConstraint:constraint];

回答1:

Try:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.carMakeLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.carModelLabel attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];

[self.view addConstraint:constraint];

Make sure self.carModelLabel and self.carMakeLabel are both in the view hierarchy of self.view.



回答2:

The signature of the method is

+(id)constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c;

and you used

    constraintWithItem:self.carMakeLabel attribute:NSLayoutRelationEqual relatedBy:self.view toItem:self.carModelLabel attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];

The data type sent to attribute is of relationship type:NSLayoutRelationEqual

Your first attribute and relatedBy arguments are switched I think.

You may have to correct that



标签: ios xcode ios6