在采取行动之前如何知道几个块是否已完成执行?

时间:2012-08-01 22:32:43

标签: iphone ios ios5 uiview objective-c-blocks

我在调用animateWithDuration:animations:completion:之前使用removeFromSuperview:移动我的用户界面的几个元素(大约4个元素)。

我的问题是,在致电removeFromSuperview:之前,我怎么知道所有这些动画都已完成?

3 个答案:

答案 0 :(得分:9)

好的,回答我自己的问题。

我最终做了这样的事情:

    // Create dispatch queue & group
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    // Two group enters
    dispatch_group_enter(group);
    dispatch_group_enter(group);

    // (notice the group parameter in dispatch_group_leave)
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.frame = CGRectMake( self.pickerView.frame.origin.x
                                           , self.view.bounds.size.height + self.pickerView.frame.size.height/2
                                           , self.pickerView.frame.size.width
                                           , self.pickerView.frame.size.height);
    } completion:^(BOOL finished){
        dispatch_group_leave(group);
    }]; 


    [UIView animateWithDuration:0.3 animations:^{
        self.navigationBar.frame = CGRectMake( self.navigationBar.frame.origin.x
                                              , -self.navigationBar.frame.size.height
                                              , self.navigationBar.frame.size.width
                                              , self.navigationBar.frame.size.height);
    } completion:^(BOOL finished){
        dispatch_group_leave(group);
    }];

    // Finishing callback
    dispatch_group_notify(group, queue, ^{
        [self.view removeFromSuperview];
    });

    // Release the group
    dispatch_release(group);

我希望这可以作为其他人的榜样。

答案 1 :(得分:1)

您也可以使用CATransaction。它将捕获任何嵌入的动画:

 [CATransaction begin];
 [CATransaction setCompletionBlock:^{ // all animations finished here }];
 [UIView animateWithDuration...
 [UIView animateWithDuration...
 ...
 [CATransaction commit];

这样您就不必自己跟踪动画了。

答案 2 :(得分:0)

创建一个调度队列,按照您正在执行的动画数量暂停它。将块添加到执行从superview中删除的队列。在每个动画的完成块中恢复暂停的队列。当最后一个完成时,排队的块将运行。