使用动画进行iOS方法调用,在完成时执行操作?

时间:2012-09-12 17:53:35

标签: objective-c ios animation

在为iOS编程时,我经常发现自己面临以下情况:

- (void)someMethod
{
    [self performSomeAnimation];

    //below is an action I want to perform, but I want to perform it AFTER the animation
    [self someAction];
}

- (void)performSomeAnimation
{
    [UIView animateWithDuration:.5 animations:^
    {
        //some animation here
    }];
}

面对这种情况,我通常最终只是复制/粘贴我的动画代码,以便我可以使用完成块处理程序,如下所示:

- (void)someMethod
{
    [self performSomeAnimation];


    //copy pasted animation... bleh
    [UIView animateWithDuration:.5 animations:^
    {
        //same animation here... code duplication, bad.
    }
    completion^(BOOL finished)
    {
        [self someAction];
    }];
}

- (void)performSomeAnimation
{
    [UIView animateWithDuration:.5 animations:^
    {
        //some animation here
    }];
}

解决此问题的正确方法是什么?我应该将代码块传递给我的-(void)performSomeAction方法,如下所示,并在完成动画时执行该块吗?

- (void)someMethod
{
    block_t animationCompletionBlock^{
        [self someAction];
    };

    [self performSomeAnimation:animationCompletionBlock];
}

- (void)performSomeAnimation:(block_t)animationCompletionBlock
{
    [UIView animateWithDuration:.5 animations:^
    {
        //some animation here
    }
    completion^(BOOL finished)
    {
        animationCompletionBlock();
    }];
}

这是解决这个问题的正确方法吗?我想我一直在避免使用它,因为我不熟悉块使用(甚至不确定我是否正确地声明了这个块)并且它似乎是一个简单问题的复杂解决方案。

2 个答案:

答案 0 :(得分:1)

你也可以这样做:

- (void)performSomeAnimationWithCompletion:(void(^)(void))animationCompletionBlock
{
    [UIView animateWithDuration:.5 animations:^
    {
        //some animation here
    }
    completion^(BOOL finished)
    {
        animationCompletionBlock();
    }];
}

而不是显式定义一个块并将其作为参数传递,您可以直接调用它(例如,这就是块动画如何为UIView工作):

- (void)someMethod
{
    [self performSomeAnimationWithCompletion:^{

        [self someAction];

    }];
}

答案 1 :(得分:0)

根据我的理解,似乎你已经有了很多答案,你只需要删除第一次调用performSomeOperation:

- (void)someMethod

{

[UIView animateWithDuration:.5 animations:^
{
    //Your animation block here
}
completion: ^(BOOL finished)
{
    //Your completion block here
    [self someAction];
}];

}