Why is constraint not working for UIView but works for UILabel?
constraints, ios, iphone
Solution
Well, the line `aView.translatesAutoresizingMaskIntoConstraints = NO;` is making the view's size zero.. So you got to add these lines of code :
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:100];
[aView addConstraint:widthConstraint];
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
[aView addConstraint:heightConstraint];
Problem
I have a simple (complete) example here which seems very odd, but surely im just missing something small... right? Can you help debug the simple code below. This code makes the aView disappear, but when if I put the aLabel in the constraint where the aView is, it works perfect. Why? Thanks for any input, this seems crazy to me. austin ``` UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 30)]; aView.backgroundColor = [UIColor redColor]; aView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:aView]; UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 30)]; aLabel.backgroundColor = [UIColor redColor]; aLabel.text = @"Label"; aLabel.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:aLabel]; NSLayoutConstraint *myConstraint =[NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]; [self.view addConstraint:myConstraint]; myConstraint =[NSLayoutConstraint constraintWithItem:aView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; [self.view addConstraint:myConstraint]; ```