Custom UIScrollView Animation

2019-05-17 09:04发布

问题:

I am using a UIScrollView with a list of buttons made to look much like a UIPickerView. I have just implemented shake to shuffle, where upon detection of a shake I set the content offset of the UIScrollView to the position of the randomShuffle using the following.

[Singlescroll setContentOffset:CGPointMake(jumpX, jumpY+randShuffle*sepValue) animated:YES];

Instead of just moving the content offset to the random position that matches a button I would like to implement a shuffle animation where the view almost 'spins' like a slot machine and then ends up on the randomShuffle button position.

I tried to do this by simply animating the offset to the top of the UIScrollView then back down again before going back to the randomShuffle position (one after another), however this didn't work and it just went straight to the randomShuffle position. I realise that I didn't try this with a timer so the animations were not delayed however I would like to avoid running a timer if possible.

Is there any inbuilt animations that can handle this? and if not please can you suggest how I might approach this before using timers? thank you.

回答1:

Instead of just using animated:YES, did you try putting it into something like:

[UIView animateWithDuration:.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
    [Singlescroll setContentOffset:maximumOffsetPoint]; //spin all the way up?
}completion:^(BOOL finished){
    if (finished)
        //kick off another animation, to spin it back down:
        [UIView animateWithDuration:.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            [Singlescroll setContentOffset:CGPointMake(jumpX, jumpY+randShuffle*sepValue)];
        }completion:nil];
    }
}];

I don't know if this answers your question, but completion blocks are super handy and might be what you need. Within the completion block, the second animation will only get called at the end of the first animation.

Also, there are several animateWithDuration: methods on UIView, but in my experience this one is more reliable for animating properties such as contentOffset and zoomToRect of scroll views.