How do I add this constraint in Xcode? It seems my relatedBy: argument is wrong

雨燕双飞 提交于 2019-12-13 03:17:56

问题


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



来源:https://stackoverflow.com/questions/13831964/how-do-i-add-this-constraint-in-xcode-it-seems-my-relatedby-argument-is-wrong

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!