An NSLayoutConstraint
has one or two views that it constrains. In your case, the views are self.logoImageView
and self.view
.
To have any effect, the constraint must be installed on a view, and not just any view. The constraint must be installed on a common ancestor of both constrained views. (Note that a view is considered to be an ancestor of itself.) And when you remove a constraint, you must remove it from the view on which it is installed.
You're trying to remove the centering constraint from self.logoImageView
, but the constraint can't have been installed on that view.
As of iOS 8.0, the preferred (and easiest) way to uninstall a constraint is to set its active
property to NO
:
self.logoImageViewYCenterConstraint.active = NO;
Prior to iOS 8.0, you have to remove it from the view where it's installed. The constraint is probably installed on self.view
. So try this instead:
[self.view removeConstraint:self.logoImageViewYCenterConstraint];
Note also that if you want to animate the image view back to the center, you'll need to uninstall topSpaceConstraint
and reinstall self.logoImageViewYCenterConstraint
.
A different way to handle this is to install both constraints simultaneously, but give one of them a lower priority. When you need to change the position of the image view, change the priorities of the constraints. Thus:
- (void)viewDidLoad {
[super viewDidLoad];
if (self.topSpaceConstraint == nil) {
self.topSpaceConstraint = [NSLayoutConstraint constraintWithItem:...];
self.topSpaceConstraint.priority = 1;
[self.view addConstraint:self.topSpaceConstraint];
}
}
- (void)setImageViewCenteredVertically:(BOOL)isCentered animated:(BOOL)animated {
if (isCentered) {
self.topSpaceConstraint.priority = 1;
self.logoImageViewYCenterConstraint.priority = UILayoutPriorityRequired;
} else {
self.topSpaceConstraint.priority = UILayoutPriorityRequired;
self.logoImageViewYCenterConstraint.priority = 1;
}
if (animated) {
[UIView animateWithDuration:1 delay:0
options:UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionAllowUserInteraction
animations:^{
[self.view layoutIfNeeded];
}
completion:nil];
}
}