Reputation: 5122
I have made a small demonstration to show what is happening in my app. Basically, I want to animate a UIView on the top left which takes up half of the screen width, to occupy the whole width and "push" the UIView on the top right off screen. Then in a later animation, I want to bring the UIView back on screen and resize the view on the left back to the half screen width it starts out as.
I have taken a few screenshots to demonstrate what happens with the way I have it now.
This is how it starts out:
Then after resizing the left view
After trying to bring it back
And here is the code which changes the size of the views
- (void)replaceWidthConstraintOnView:(UIView *)view withConstant:(float)constant {
[self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
if ((constraint.firstItem == view) && (constraint.firstAttribute == NSLayoutAttributeWidth)) {
constraint.constant = constant;
}
}];
}
- (IBAction)changeViewSize {
CGFloat blueViewWidth = self.blueView.bounds.size.width;
if (blueViewWidth == self.view.bounds.size.width) {
blueViewWidth = blueViewWidth / 2;
[self replaceWidthConstraintOnView:self.blueView withConstant:blueViewWidth];
}
else {
blueViewWidth = blueViewWidth * 2;
[self replaceWidthConstraintOnView:self.blueView withConstant:blueViewWidth];
}
}
I am wondering why the blue view doesn't come back to cover only half of the screen. I appreciate any help!
Upvotes: 0
Views: 1147
Reputation: 2381
I'm not sure why it's not working as you wrote it, but you could use some relative constraints instead of float sizes.
First of all, make sure you're setting the translatesAutoresizingMaskIntoConstraints property to NO on the blue view.
Something like will make the blue view half the size of the main view:
[self.view addConstraint:[NSLayoutConstraint
constraintWithItem:self.blueView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:0.5f
constant: 0.0]];
To make if fill the whole view you can loop through all the constraints and modify the multipliers/constants as you want. This, for example, will make the blue view fill its parent by setting the multiplier for the NSLayoutAttributeWidth constrain to 1.0:
for(NSLayoutConstraint *constraint in self.view.constraints)
{
if(constraint.firstAttribute == NSLayoutAttributeWidth && constraint.secondAttribute == NSLayoutAttributeWidth &&
constraint.firstItem == self.blueView && constraint.secondItem == self.blueView)
{
constraint.multiplier = 1.0;
}
}
Upvotes: 1