UIView中的iOS完成块animateWithDuration会被调用得太早

我试图做一些animation时,表格视图单元格被选中。 出于某种原因,完成块被调用得太早了。 即使将持续时间设置为10秒,也会立即调用完成块。

[UIView animateWithDuration:10.0 animations:^{ message.frame = newFrame; } completion:^(BOOL finished) { NSLog(@"DONE???"); }]; 

任何想法,为什么发生这种情况? 谢谢。

从UIView文档 :

完成

animation序列结束时要执行的块对象。 该块没有返回值,并且只接受一个布尔参数,该参数指示在调用完成处理程序之前animation是否实际完成。 如果animation的持续时间为0,则在下一个运行循环开始时执行该块。 该参数可能是NULL。

这意味着不能保证代码只有在animation完成时才会被执行。 我build议你检查“已完成”参数作为执行条件。

是。 它被称为太早,因为它被打断了。 可能是通过模态演示过渡或者其他方式。 根据您的需求,以下可能是您喜欢的解决scheme。 我们通过手动延迟执行animation代码来避免冲突,如下所示:

 // To get this in Xcode very easily start typing, "dispatch_aft..." // Note the "0.2". This ensures the outstanding animation gets completed before we start ours dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [UIView animateWithDuration:1.0 delay:0 options:0 animations:^{ // Your animation code } completion:^(BOOL finished) { // Your completion code }]; }); 

如果animation没有效果,也可以提前调用完成,例如将视图的alpha设置为已有的值。