问题
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