UIButton使UIScrollView反弹

Ale*_*erZ 2 uibutton uiscrollview bounce ios

我有一个横向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];
    }
}
Run Code Online (Sandbox Code Playgroud)

scrollView当我们在第一页(页面= 0)并按下左键时,我希望按钮使显示弹跳效果.

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

编辑:

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

首先我加入了 goLeftAction:

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

接下来:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*arp 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];
Run Code Online (Sandbox Code Playgroud)

反弹方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)