2012-09-12 36 views
2

当iOS编程,我经常发现自己面临着以下情况: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(); 
    }]; 
} 

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

+0

你说的动画总是相同的,但完成变化?如果是这样,你的解决方案对我来说看起来很不错。 –

+0

我认为我的语法不正确。我只是看着它,我应该像这样声明我的块:void(^ myBlock)(void),但是我的方法声明看起来像什么? - (void)performSomeAnimation :(无效)(^ myBlock)(void)似乎没有工作(我敢肯定我正在屠杀语法哈哈) – MikeS

回答

1

你也可以这样做:

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

而不是明确地定义一个块,将它作为参数,可以直接调用它(这是块动画如何为UIView的工作,例如) :

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

     [self someAction]; 

    }]; 
} 
+0

嗯没关系。这可能比尝试创建块并使用我尝试的方法传递它更好。由于某种原因,它看起来更清洁并且感觉更自然。 – MikeS

+0

是的,它有点干净。对于这些东西块真的很有帮助。不要害怕使用它们! – jere

+0

已将此代码添加到我的代码中,并且一切似乎都正常。谢谢! (:) – MikeS

0

从我能理解,似乎你已经非常有答案,你只需要删除对performSomeOperation第一个电话:

- (void)someMethod 

{

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

}

+0

那么,这个问题(因为乔希比我更优雅地说)是我有一个动画我执行总是一样的,但完成块不断变化,所以我需要一种方式来传递一个完成块,以免不断重复我的动画代码。 – MikeS

相关问题