How to add an animation to the UIView in viewDidAppear?
I tried to add a animation to viewDidLoad and viewDidAppear, but it doesn't work:
- (void)viewDidAppear:(BOOL)animated{
[UIView beginAnimations:@"transition" context:NULL];
[U开发者_如何学编程IView setAnimationTransition:110 forView:self.view cache:YES];
[UIView commitAnimations];
}
Why?
I had the same problem and I think I found the solution on this SO question.
When viewDidAppear gets called you still don't see anything on the screen (despite the name), but you are about to. You can then use a performSelector:withDelay or an NSTimer to launch your animation. The delay can just be 0.1 and your animation will play just when the screen appears.
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"View did appear!");
[self performSelector:@selector(animationCode) withObject:nil afterDelay:0.1f];
}
- (void)animationCode {
// you animation code
}
You are not telling the view which state it should animate to so it won't do anything. You need to place code between beginAnimations:context:
and commitAnimations
that changes the appearance of the view (e.g. by removing one subview and adding another).
You're not using
beginAnimations:
andcommitAnimations
correctly. You're supposed to put something in between them that normally wouldn't be animated: e.g. withself.view.alpha = 0.5
you get a fading effect. They have no effect on anything that isn't between them.By the time
viewDidAppear:
is called, your view, well... has appeared. It's too late to animate anything. What you actually want to do is something like this:- (void)showMyViewWithAnimation { [UIView beginAnimations:nil context:nil]; [UIView setAnimationTransition:110 forView:childView cache:YES]; [parentView addSubview:childView]; [UIView commitAnimations]; }
In the example above,
childView
is what in your example is calledself.view
.Please write out the name of the transition; no one knows what 110 is by looking at it. It's bad style. </pedantry>
精彩评论