Repeating UIAnimation block, and a way to stop it again

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 07:56:53

问题


I wanted to do a small loader animation to put in my app. I have done repeating animations before with CGAnimations without problems, this time I was going for the block approach.

I am doing a small test but can make the following code repeat:

- (void) startLoading {

    __block int count = 0;

    [UIView animateWithDuration:0.4
                          delay: 0.0
                        options: UIViewAnimationOptionRepeat
                     animations:^{
                         count++;
                     }
                     completion:^(BOOL finished){

                         if (count > 5)
                             count = 0;
                         NSLog(@"%d", count);

                     }];

}

- (void) stopLoading {

}

The above only fires the completion block once, it does not repeat.

How do I get the block to repeat so that count increments?

If I get this working and put my animation into the repeating block, What goes into stopLoading: to stop the animation again?

Thanks for any help given:)


回答1:


Here's a finite repeating animation:

- (void) animate: (int) count {
    CGPoint origC = v.center;
    void (^anim) (void) = ^{
        v.center = CGPointMake(100,100);
    };    
    void (^after) (BOOL) = ^(BOOL finished) {
        v.center = origC;
        if (count)
            [self animate:count-1];
    };
    int opts = UIViewAnimationOptionAutoreverse;
    [UIView animateWithDuration:1 delay:0 options:opts 
                     animations:anim completion:after];
}

There's a recursion here, so we don't want to go overboard or we'll run out of memory, but if we limit our count (in your example it was 5) we should be fine.



来源:https://stackoverflow.com/questions/6616213/repeating-uianimation-block-and-a-way-to-stop-it-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!