问题
I have an UIImageView that I want to animate slowly with a pan effect at the background. My background image view has four constraints:
- Distance from top to top layout guide (zero)
- Distance from bottom to bottom layout guide (zero)
- Width (constant at 850)
- Leading space to superview (zero, connected to code as
backgroundImageViewLeftMargin
outlet)
The image view's view mode is set to "aspect fill". When I run my app, there is no problem, the static image is displayed. I add the following code to animate my view:
-(void)animateBackgroundHorizontally:(BOOL)forward{
self.backgroundImageViewLeftMargin.constant = forward ? -500 : 0;
[self.backgroundImage setNeedsUpdateConstraints];
[UIView animateWithDuration:30 animations:^{
[self.backgroundImage layoutIfNeeded];
} completion:^(BOOL finished) {
[self animateBackgroundHorizontally:!forward];
}];
}
Then I call [self animateBackgroundHorizontally:YES];
at viewWillAppear:
. Here is what happens:
The image starts animating from an unexpected (yet always the same) location (top edge at about the middle of the screen where it should be at the top of the screen), animates to its final position correctly, then when animating back to its original location, it does animate correctly. The only property that I'm animating is the left margin. When I don't call the animation code, it displays correctly. Why does the animation start from an incorrect location as seen on the image? I've tried setting self.backgroundImage.translatesAutoresizingMaskIntoConstraints
to both YES
(I got the unable to simultaneously satisfy constaints error) and NO
but it didn't work. This problem is persistent on both iOS 6 and iOS 7.
回答1:
I've put the animation start code in viewDidAppear:
instead of viewWillAppear:
and the problem is gone. Insteresting. Tried on both iOS 6 and iOS 7 and they both work well now.
来源:https://stackoverflow.com/questions/19967837/uiview-animating-one-constraint-affects-another-constraint