objective-canimatewithdurationremovefromsuperview

Remove from superview not working in animation completion handler


I have a UIView with several UILabels added. I am simply moving them all to the center of the screen with an animation, and then attempting to remove them from their superview in the animation completion handler.

for (label in [self.view subviews])
{
    if([label isKindOfClass:[UILabel class]])
    {
        CGRect frame = CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, label.frame.size.width, label.frame.size.height);
        [UIView animateWithDuration:2.0
                              delay:0.0
                            options: UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             [self->label setFrame:frame];
                         }
                         completion:^(BOOL finished){
                             dispatch_async(dispatch_get_main_queue(),^{
                                 [self->label removeFromSuperview];
                             });
                         }
         ];
    }
}

The problem that I am having is that at the end of the animation the UILabels remain. If I put the removeFromSuperView call outside of the animation block then it works, but of course then they are removed before the animation has a chance to complete.


Solution

  • You've got label as the variable in the for-in and self->label in the blocks. Apparently, you weren't operating on the label you thought you were.