Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView removeFromSuperView animation delay

I have a method which animates one of the subviews of UIWindow and then removes it from UIWindow using removeFromSuperview. But when I put removeFromSuperview after animation block, the animation never shows, because removeFromSuperview removes the UIView from UIWindow before the animation plays :-( How can I delay removeFromSuperview so the animation plays first, and then subview is removed? I tried [NSThread sleepForTimeInterval:1]; after animation block but that didn't have desired effect, because animation sleeps too for some reason.

My code for this method:

  - (void) animateAndRemove
    {
     NSObject *mainWindow = [[UIApplication sharedApplication] keyWindow];

     [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.8]; 
     UIView *theView = nil;
     for (UIView *currentView in [mainWindow subviews])
     {
      if (currentView.tag == 666)
      {
       currentView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.0];
       theView = currentView;
       }
     }
     [UIView setAnimationTransition:  UIViewAnimationTransitionNone forView:theView cache:YES];
      [UIView commitAnimations]; 



 //[NSThread sleepForTimeInterval:1];

 [theView removeFromSuperview];


    }
like image 615
Mike Avatar asked Nov 28 '22 19:11

Mike


1 Answers

You should use the delegation mechanism in animation blocks to decide what to do when the animation ends. For your case, use

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:theView];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];
 ....

This ensures [theView removeFromSuperview] will be called after the animation is completed.

like image 94
kennytm Avatar answered Dec 04 '22 06:12

kennytm