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];
}
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.
If you're targetting iOS 4.0 upwards you can use animation blocks:
[UIView animateWithDuration:0.2
animations:^{view.alpha = 0.0;}
completion:^(BOOL finished){ [view removeFromSuperview]; }];
(above code comes from Apple's UIView documentation)
精彩评论