简体   繁体   中英

Custom UIView doesn't get removed from superview when loaded again while animating

The question explains it all actually.

I load a custom UIView on top of my current view, animated, using this code:

- (void)showView
{
    self.blurView.alpha = 0.f;

    [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^
     {
         self.blurView.alpha = 1.f;
     } completion:^(BOOL finished) {
         [UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^
          {
              self.blurView.alpha = 0.f;
          } completion:nil];
     }];
}

It works, but when I perform -(void)showView again while it is still animating, the custom view doesn't get removed from the screen.

It just stays like this:

在此处输入图片说明

I figured out what the problem was.

blurView is a public variable and every time I did -(void)showView it used the same variable, setting the alpha to 0.f just once, thus never changing the alpha of the first show.

I declared the variable blurView in the method itself and now it works because every blurView gets it's own pointer.

-(void)someMethod
{
    //Create a live blur view
    FXBlurView *blurView = [[FXBlurView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    blurView.center = CGPointMake(self.view.window.frame.size.width / 2, self.view.window.frame.size.height / 2);
    blurView.layer.cornerRadius = 20.f;
    [self.view.window addSubview:blurView];

    [self showView:(blurView)];
}

- (void)showView:(FXBlurView *)blurView
{
    //Make full transparent before showing
    blurView.alpha = 0.f;

    //Start animation
    [FXBlurView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^
     {
         blurView.alpha = 1.f;
     } completion:^(BOOL finished) {
         if (finished)
         {
             //End animation
             [FXBlurView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^
              {
                  blurView.alpha = 0.f;
              } completion:nil];
         }
     }];
}

You should add to the top of your function this line:

[self.view.layer removeAllAnimations];

It will remove all of the active animations.

It doesn't work because you have implemented a delay, use animation block with delay - it will create animation keys that could be removed with this function above.

[UIView animateWithDuration:0.3 delay:0.0
                    options:UIViewAnimationOptionAllowUserInteraction
                 animations:^
 {
     // ...
 } completion:NULL];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM