简体   繁体   中英

Understanding the completion block of [UIView animateWithDuration:completion:]

I'm trying to understand UIView animateWithDuration:completion . What I'm trying to do is drag a UIView into another UIView. If they intersect, set the make the dragging UIView's alpha to 0, and then reset the dragging UIView to its original spot. The idea is to drag and drop an item into a bucket. To start I'm just setting the alpha to 0 and then resetting it. This is the code I have for the pan gesture recognizer of the dragging view:

else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        // Update the description view
        if (CGRectIntersectsRect(panViewPiece.frame, _descriptionView.frame)) {
            [UIView animateWithDuration:0.25 animations:^{
                self.dragDescriptionView.alpha = 0.0;
            }completion:^(BOOL finished) {
                if (finished) {
                    panViewPiece.center = _dragDescriptionViewOriginalCenter;
                    self.dragDescriptionView.alpha = 1.0;
                }
            }];
            [self updateDescriptionView];
        }
}

So I thought the way the completion block worked was when the first animateWithDuration is finished, the completion block would be called. So I'm trying to set the alpha to 0 in the first part, and then once that's done, put the panViewPiece back to its original spot and set its alpha to 1. What happens is after the rects intersect, the alpha goes to 0 and then goes back to 1 as it snaps back to its original center. I don't want the view visible while its snapping back to its original position. Am I understanding the completion block correctly? Or is this not the way it works? Thanks!

In the completion block, you're setting the dragDescriptionView's alpha back to 1.0, after you animated it down to 0.0. Is that what you want? In your question it sounds like you want the panViewPiece to have an alpha of 1.0, but that's not what your code is doing.

I'm not quite clear what you are seeing - the fade to alpha 0 works OK, but then you say it is visible again before it returns to the original position? Does it animate back to visible or animate back to its original position?

If it just appears, then suddenly goes back to the right position, then my guess is that some other bit of code (not shown in your question) is setting the alpha back to 1 before your animation block has finished - you do realise that UIView block animation calls are asynchronous, so the code following will be executing before or during the performance of the animation?

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