2

我有一个水平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];
    }
}

scrollView当我们在第一页(page = 0)并按左时,我希望按钮显示弹跳效果。

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

编辑:

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

首先我添加到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];
}
4

1 回答 1

6

这是个有趣的问题。您是否在 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];
}
于 2013-08-12T23:33:29.010 回答