UIScrollview setContentOffset与非线性动画?

Diw*_*ann 27 iphone uiscrollview ipad ios

当您实际滚动到下一页时,我试图重现滚动视图的平滑动画,并启用分页.它似乎是UIViewAnimationCurveEaseInOut,但我需要一个"下一页"按钮并以编程方式触发滚动.

这是我的代码:

-(void) scrollToPage:(int)page
{
    UIScrollView *scrollView = contentView;
    CGPoint offset = CGPointMake(scrollView.bounds.size.width * page, scrollView.contentOffset.y);
    [scrollView setContentOffset:offset animated: YES];     
    [self pageControlUpdate];
}

-(void) scrollToNextPage 
{
    [self scrollToPage:(pageControl.currentPage + 1)];
}
Run Code Online (Sandbox Code Playgroud)

我无法重现平滑UIViewAnimationCurveEaseInOut,无论是用setContentOffset还是用scrollRectToVisible......它都会带着丑陋的线性动画进入下一页

我甚至尝试手动设置动画:

[UIView animateWithDuration:.5 delay:0 options:UIViewAnimationCurveEaseInOut animations:^{
    scrollView.contentOffset = offset;
} completion:^(BOOL finished) {    } ];
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

小智 21

每次制作自己的动画时,都必须传递NO作为animated:参数:

- (void)scrollToPage:(int)page
{
    UIScrollView *scrollView = contentView;
    CGPoint offset = CGPointMake(scrollView.bounds.size.width * page, 
                                 scrollView.contentOffset.y);

    [UIView animateWithDuration:.5
                          delay:0
                        options:UIViewAnimationCurveEaseInOut
                     animations:^{
                         [scrollView setContentOffset:offset animated:NO];
                     } completion:nil];

    [self pageControlUpdate];
}
Run Code Online (Sandbox Code Playgroud)


And*_* R. 6

使用公共API,我认为目前不可能.假设您在动画过程中不需要用户交互,那么您最好动画制作UIScrollView子视图的位置(即滚动视图的内容),然后contentOffset在完成时调整无动画.你可以这样做:

- (void) scrollToPage:(int)page {
    UIScrollView *scrollView = contentView;
    scrollView.userInteractionEnabled = NO;
    CGPoint offset = CGPointMake(scrollView.bounds.size.width * page, scrollView.contentOffset.y);
    CGFloat delta = offset.x - scrollView.contentOffset.x;

    __block int animationCount = 0;
    for (UIView *view in scrollView.subviews) {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            animationCount++;
            CGRect frame = view.frame;
            frame.origin.x -= delta;
            view.frame = frame;
        } completion:^(BOOL finished) {
            animationCount--;
            if (animationCount == 0) {
                scrollView.contentOffset = offset;
                for (UIView *view in scrollView.subviews) {
                    CGRect frame = view.frame;
                    frame.origin.x += delta;
                    view.frame = frame;
                }
                scrollView.userInteractionEnabled = YES;
            }
        }];
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以确认这是按预期工作的,我自己测试了.