开发者

How to add an animation to the UIView in viewDidAppear?

开发者 https://www.devze.com 2022-12-19 03:53 出处:网络
I tried to add a animation to viewDidLoad and viewDidAppear, but it doesn\'t work: - (void)viewDidAppear:(BOOL)animated{

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).


  1. You're not using beginAnimations: and commitAnimations correctly. You're supposed to put something in between them that normally wouldn't be animated: e.g. with self.view.alpha = 0.5 you get a fading effect. They have no effect on anything that isn't between them.

  2. 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 called self.view.

  3. Please write out the name of the transition; no one knows what 110 is by looking at it. It's bad style. </pedantry>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号