16

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jesse Head
  • 598
  • 2
  • 6
  • 18

1 Answers1

12

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

Jesse Head
  • 598
  • 2
  • 6
  • 18
  • 1
    Yes, this helped me as well. Apparently you need at least two constraints or the view won't display. – JasonD Dec 31 '12 at 22:24
  • 1
    You need as many as is required to remove ambiguity. This can be as little as two, but sometimes more. (Labels, for instance require a minimum of two, it can infer the size from the text, but you need to give it an X and Y) – LightningStryk Apr 29 '15 at 17:12