2

在为 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();
    }];
}

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

4

2 回答 2

1

你也可以这样做:

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

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

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

        [self someAction];

    }];
}
于 2012-09-12T18:26:33.077 回答
0

据我所知,您似乎已经有了答案,您只需要删除对 performSomeOperation 的第一个调用:

- (void)someMethod

{

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

}

于 2012-09-12T18:35:47.593 回答