UIView animation delay delay removeFromSuperView

I have a method that animates one of the UIWindow subzones and then removes it from UIWindow using removeFromSuperview . But when I put removeFromSuperview after the animation block, the animation never shows up because removeFromSuperview removes the UIView from the UIWindow before playing the animation :-( How can I delay removeFromSuperview so that the animation plays first and that subview is removed? I tried [NSThread sleepForTimeInterval:1]; after the animation block, but this did not have the desired effect, because the animation also goes off 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]; } 
+4
source share
2 answers

You must use the delegation mechanism in the 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 that [theView removeFromSuperview] will be called after the animation finishes.

+16
source

If you aim iOS 4.0 up, you can use animation blocks:

 [UIView animateWithDuration:0.2 animations:^{view.alpha = 0.0;} completion:^(BOOL finished){ [view removeFromSuperview]; }]; 

(the above code comes from Apple UIView documentation)

+7
source

Source: https://habr.com/ru/post/1307143/


All Articles