【问题标题】:iOS Method Call With Animation, Perform Action on Completion?带有动画的iOS方法调用,完成时执行操作?
【发布时间】:2012-09-13 02:35:47
【问题描述】:

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

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

【问题讨论】:

  • 你是说动画总是一样的,但是完成度会变?如果是这样,您的解决方案对我来说是一个不错的解决方案。
  • 我认为我的语法不正确。我刚刚研究了一下,我应该像这样声明我的块:void (^myBlock) (void),但是我的方法声明会是什么样子? - (void)performSomeAnimation:(void)(^myBlock)(void) 似乎不起作用(我确定我正在扼杀这种语法哈哈)

标签: objective-c ios animation


【解决方案1】:

你也可以这样做:

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

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

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

        [self someAction];

    }];
}

【讨论】:

  • 嗯好吧。这可能比尝试创建一个块并使用我尝试的方法传递它更好。由于某种原因,它看起来更干净,感觉更自然。
  • 是的,它有点干净。对于这类事情,积木真的很有帮助。不要害怕使用它们!
  • 已经将此添加到我的代码中,一切似乎都在工作。谢谢!
【解决方案2】:

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

- (void)someMethod

{

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

}

【讨论】:

  • 嗯,问题(正如 Josh 所说的比我更优雅)是我执行的动画始终相同,但完成块不断变化,所以我需要一种方法传递一个完成块,以免不断重复我的动画代码。
猜你喜欢
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多