UIScrollView disable scrolling in just one directi

2019-01-21 19:55发布

I've been unable to find an answer for this (maybe someone has hacked a solution together).

Is it possible to disable scrolling in a UIScrollView in one direction? I am not talking about disabling vertical or horizontal scrolling, but one direction only. So for example, in a UIScrollView, I want to be able to drag the scrollview in a downwards direction, but not in an upwards direction

Thanks

9条回答
劳资没心,怎么记你
2楼-- · 2019-01-21 20:01

An alternative might be:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 10) {
        scrollView.bounces = NO;
    }

    else scrollView.bounces = YES;
}

But remember that this will only work for the scrollViews, which have a bigger content than their frames.

查看更多
Juvenile、少年°
3楼-- · 2019-01-21 20:03

The above solutions will reset you to zero,zero if the user accidentally scrolls vertically. Try this...

- (void)scrollViewDidScroll:(UIScrollView *) scrollView {
    if (scrollView.contentOffset.y > 0) {
        [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
    }
}
查看更多
该账号已被封号
4楼-- · 2019-01-21 20:07

This works for me:

    -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
        scrollView.bounces = YES;
    }

    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{

        if (scrollView.contentOffset.y < 0) {
            [scrollView setContentOffset:CGPointMake(0, 0)];
            scrollView.bounces = NO;
        }

        if (scrollView.contentOffset.y == 0){
            scrollView.bounces = YES;
        }

        else scrollView.bounces = YES;
    }
查看更多
该账号已被封号
5楼-- · 2019-01-21 20:16

If you set the contentSize of the scroller equals to the size of the content, in one of the direction, the scroll will disappear in that direction because there will be nothing to scroll.

查看更多
冷血范
6楼-- · 2019-01-21 20:18

Fortunately, we can use scrollRectToVisible to avoid jittery behavior after the scroll has been limited:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > 60) {
        [scrollView setContentOffset:CGPointMake(0, 60)];

        CGFloat pageWidth  = scrollView.frame.size.width;
        CGFloat pageHeight = scrollView.frame.size.height;
        CGRect rect = CGRectMake(0, 0, pageWidth, pageHeight);
        [scrollView scrollRectToVisible:rect animated:YES];
    }
}
查看更多
【Aperson】
7楼-- · 2019-01-21 20:23

Turns out a simple solution was actually possible and easy:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > 60) {
        [scrollView setContentOffset:CGPointMake(0, 60)];
    }
}
查看更多
登录 后发表回答