0

Why this piece of code doesn't work as a container of a vertically aligned UILabels? What's wrong?

self.daysContainer = [[UIView alloc]init];
[self.daysContainer setTranslatesAutoresizingMaskIntoConstraints:NO];
UILabel *dayview1 = [[UILabel alloc]init];
UILabel *dayview2 = [[UILabel alloc]init];
[dayview1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[dayview2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.daysContainer addSubview:dayview1];
[self.daysContainer addSubview:dayview2];
dayview1.text = @"DayView 1";
dayview2.text = @"DayView 2";
dayview1.backgroundColor = [UIColor redColor];
NSDictionary *elementsDict = NSDictionaryOfVariableBindings(dayview1, dayview2);
[self.daysContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[dayview1]-[dayview2]-|"                                                                  options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil                                                                 views:elementsDict]];
[self.daysContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[dayview1]-|"                                                                     options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil                                                                    views:elementsDict]];
[self.daysContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[dayview2]-|"                                                                    options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil                                                                     views:elementsDict]];
JaredH
  • 2,338
  • 1
  • 30
  • 40

2 Answers2

0

It appears the problem is that the only source of vertical constraints

[self.daysContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[dayview1]-[dayview2]-|"                                                                  options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil                                                                 views:elementsDict]];

does not contain information in the visual format string about how tall either of the two views should be. If they should be equal, using the visual format @"V:|-[dayview1(dayview2)]-[dayview2]-|" should handle it. You could also specify to add any space to the end, @"V:|-[dayview1]-[dayview2]-(>=20)-|"

Mike Sand
  • 2,750
  • 14
  • 23
  • in self.view it works and the problem is when i try to add the constraint to a specified container. The (>=20) is not needed because: H:|-[dayview1]-| – Daniel Toranzo Perez Feb 03 '15 at 13:55
0

Problem solved: self.daysContainer = [[UIView alloc]init]; was creating a new instance, so the constraints are not being added in the storyboard.

Thanks and great support!