Trying to add simple constraint but got this error message

不问归期 提交于 2019-12-12 01:28:21

问题


I'm trying simple experiment just to try how I can add constraints into an object. So, I create just a single UIView (yellow coloured) with vertical space constraint = 200 from storyboard like this :

here's my interface file :

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIView *screenView;
@property (strong, nonatomic) IBOutlet UIView *container;

@end

and I want to programatically modify Vertical Space Constraint of _container by having this code on my viewDidLoad :

NSLayoutConstraint *myConstraint =[NSLayoutConstraint
                                   constraintWithItem:_screenView
                                   attribute:NSLayoutAttributeWidth
                                   relatedBy:NSLayoutRelationEqual
                                   toItem:_container
                                   attribute:NSLayoutAttributeWidth
                                   multiplier:5
                                   constant:15];
[_container addConstraint: myConstraint];

but when I run it into simulator, I got this error message :

> 2013-09-19 05:48:26.488 container[6036:c07] *** Terminating app due to
> uncaught exception 'NSGenericException', reason: 'Unable to install
> constraint on view.  Does the constraint reference something from
> outside the subtree of the view?  That's illegal.
> constraint:<NSLayoutConstraint:0x7168860 UIView:0x7168b50.width ==
> 5*UIView:0x7169360.width + 15> view:<UIView: 0x7169360; frame = (0 0;
> 0 0); autoresize = TM+BM; layer = <CALayer: 0x7168bb0>>'

what did I do wrong? thank you...

UPDATE : here's what I mean with _container

and here's _screenView


回答1:


Your problem is that _screenView is the superview of _containerView, so your constraint should be added to it, not _containerView. Also, you say, " I want to programatically modify Vertical Space Constraint of _container by having this code on my viewDidLoad", but what you're doing is adding a completely different constraint (a width constraint) instead of modifying the one you have. If you want to modify the vertical spacing constraint, you can make an IBOutlet to it, and modify it's constant value in code.



来源:https://stackoverflow.com/questions/18883664/trying-to-add-simple-constraint-but-got-this-error-message

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