I have a horizontal UIScrollView with paging. There are two buttons. One scrolls scrollView to the left another to the right.

The code for the left one:

- (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];
    }
}

I want button to make scrollView show a bouncing effect when we are at the first page (page=0) and push LEFT.

Please help find the way to achieve this.

EDIT:

Here is the code if someone need it.

First I added to goLeftAction:

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

And this next:

- (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];
}
有帮助吗?

解决方案

This is an interesting question. Have you seen this similar question on SO? It bounces vertically, not horizontally, but the concept is the same.

  1. Set pagingEnabled and scrollEnabled to NO
  2. Animate bounce using scrollRectToVisible:animated:
  3. Set pagingEnabled and scrollEnabled back to YES

This discussion also has some sample code that may be useful.

EDIT:
I had a play around with the code in your edit above, and managed to get the bounce working in the correct direction. I had to use setContentOffset:animated: instead of scrollRectToVisible:animated:, and I also increased the timer interval to 0.3 (0.1 is not enough time for the bounce to reach the full distance before unbounceScrollView is called).

My code in goLeftAction::

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

The bounce methods:

- (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];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top