Reputation:
Just to try it out I create a Button programmatically as below
UIBUtton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"Button" forState:UIControlStateNormal];
[button sizeToFit];
[self.view insertSubview:button belowSubview:_testlabel];
I already have an existing label inside my view named _testlabel. I am using autolayout and I wanted to center my newly added button's X to the _testlabel, I tried the below code in every possible way I could:
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:_testlabel attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual toItem:button
attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];
All I could do was center _testlabel's X to the newly added button, not the other way around. What am I missing here?
Upvotes: 2
Views: 554
Reputation: 4646
You may need to do this to both your button and your label:
[button setTranslatesAutoresizingMaskIntoConstraints:FALSE];
[_testlabel setTranslatesAutoresizingMaskIntoConstraints:FALSE];
and then add additional resizing constraints using AutoLayout constraint formatting lanaguage using:
[self.view addConstraints: ... constraintsWithVisualFormat ...];
and/or also using more
[self.view addConstraint: ... constraintWithItem ...]
Upvotes: 1