Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add constraints programmatically to a programmatically created UIView?

I have created a UIView using the following code within viewDidLoad (where 'secondview' obviously is the name of the UIView):

secondview = [[UIView alloc] initWithFrame:self.view.frame];
    [secondview setBackgroundColor: [UIColor yellowColor]];
    secondview.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:secondview];

Then within viewDidAppear I added constraints to this view:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:secondview attribute:NSLayoutAttributeRight
    relatedBy:NSLayoutRelationEqual
    toItem:self.view
    attribute:NSLayoutAttributeRight
    multiplier:1.0f constant:-20.0f];
[self.view addConstraint:constraint];

However, the constraints are not applied to the view (atleast not that I can see). Instead, the view simply seems to disappear from the screen. If the constraint code is commented out however, the view once again loads with the appropriate frame (obviously without the constraints being applied). When applying the same constraints to a Button or ImageView, the constraints are applied perfectly. This has lead me to think that the issue is because of 'initWithFrame' when creating the View, as neither the button nor ImageView actually require it's size to be specified.

What are your thoughts? What should I do differently?

like image 268
Jesse Head Avatar asked Oct 09 '12 08:10

Jesse Head


1 Answers

For anyone who comes across this... I needed to add more than one constraint. That did the trick.

like image 106
Jesse Head Avatar answered Oct 15 '22 03:10

Jesse Head