UI按钮使UIScrollView反弹



我有一个带分页的水平UIScrollView。有两个按钮。一个向左滚动scrollView,另一个向右滚动。

左边的代码:

- (IBAction)goLeftAction:(id)sender
{
    CGFloat pageWidth = _theScrollView.frame.size.width;
    int page = floor((_theScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    if(page>0){
        page -=1;
        [_theScrollView scrollRectToVisible:CGRectMake(_theScrollView.frame.size.width*page, 0, self.view.frame.size.width, self.view.frame.size.height) animated:YES];
    }
}

当我们在第一页(page=0)并按下LEFT时,我想要按钮使scrollView显示反弹效果。

请帮助找到实现这一目标的方法。

编辑:

如果有人需要,这是代码。

首先我添加到goLeftAction:

[_theScrollView setPagingEnabled:NO];
[_theScrollView setScrollEnabled:NO];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(bounceScrollView) userInfo:nil repeats:NO];

下一个:

- (void)bounceScrollView
{
    [self.theScrollView scrollRectToVisible:CGRectMake(100, 0, self.view.frame.size.width, self.view.frame.size.height) animated:YES];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(unbounceScrollView) userInfo:nil repeats:NO];
}
- (void)unbounceScrollView
{
    [self.theScrollView scrollRectToVisible:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) animated:YES];
    [_theScrollView setPagingEnabled:YES];
    [_theScrollView setScrollEnabled:YES];
}

这是一个有趣的问题。你在SO上看到过类似的问题吗?它垂直反弹,而不是水平反弹,但概念是一样的。

  1. 将pagingEnabled和scrollEnabled设置为NO
  2. 使用scrollRectToVisible:animated:制作反弹动画
  3. 将pagingEnabled和scrollEnabled设置回YES

本讨论还有一些可能有用的示例代码。

编辑:
我对你上面编辑的代码进行了一次尝试,并设法使反弹朝着正确的方向进行。我不得不使用setContentOffset:animated:而不是scrollRectToVisible:animated:,并且我还将计时器间隔增加到0.3(0.1的时间不足以让反弹在调用unbounceScrollView之前达到全程)。

我在goLeftAction::中的代码

[self.scrollView setPagingEnabled:NO];
[self.scrollView setScrollEnabled:NO];
[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(bounceScrollView) userInfo:nil repeats:NO];

反弹方法:

- (void)bounceScrollView
{
    [self.scrollView setContentOffset:CGPointMake(-100, 0) animated:YES];
    [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(unbounceScrollView) userInfo:nil repeats:NO];
}
- (void)unbounceScrollView
{
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.scrollView setPagingEnabled:YES];
    [self.scrollView setScrollEnabled:YES];
}

最新更新