Swift中的UIView animateWithDuration completion闭包会立即调用。

14
我希望UIView动画完成后才会调用指定的闭包,但它似乎立即执行了...
 UIView.animateWithDuration(
        Double(0.2),
        animations: {
            self.frame = CGRectMake(0, -self.bounds.height, self.bounds.width, self.bounds.height)
        },
        completion: { finished in
            if(finished) {
                self.removeFromSuperview()
            }
        }
    )

还有其他人经历过这种情况吗?我读到别人使用中心而不是框架来移动视图更成功,但我用这种方法仍然遇到了同样的问题。


你在哪里执行这段代码? - akashivskyy
4
确保框架实际上会更改,因为当没有动画时,完成块会立即调用。 - akashivskyy
1
在一个自定义的UIView类中,我在init()方法中将视图动画到指定位置,然后当任何地方发生轻击时调用上述代码。该框架肯定也在改变... - user300285
只是补充一下,同样的情况也会出现在不同的动画中。例如,改变视图的 alpha 值。 - user300285
2个回答

13

如果其他人也遇到了这个问题,那么如果任何东西中断了动画,完成闭包会立即被调用。在我的情况下,这是由于自定义Segue正在取消的视图控制器的模态转换略微重叠造成的。对于我来说,使用UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations:{}中的delay部分没有效果。我最终使用GCD延迟动画几分之一秒。

// To avoid overlapping with the modal transiton
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {

    // Animate the transition
    UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {

         // Animations

         }, completion: { finished in

         // remove the views
         if finished {            
             blurView.removeFromSuperview()
             snapshot.removeFromSuperview()
         }
    })
})

0
最后,我将动画从hitTest()移到了touchesBegan()中的UIView中来解决了这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接