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条回答
ら.Afraid
2楼-- · 2019-01-21 20:24

this works for me

static CGPoint lastOffset;

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    scrollView.scrollEnabled = YES;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    scrollView.scrollEnabled = YES;
    lastOffset = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint nowOffset = scrollView.contentOffset;
    NSLog(@"delta %f", lastOffset.x - nowOffset.x);
    if ((lastOffset.x - nowOffset.x) < 0) {
        //uncomment to prevent scroll to left
        //scrollView.scrollEnabled = NO;
    } else if ((lastOffset.x - nowOffset.x) > 0) {
        //uncomment to prevent scroll to right
        //scrollView.scrollEnabled = NO;
    } else {
        scrollView.scrollEnabled = YES;
    }
}
查看更多
趁早两清
3楼-- · 2019-01-21 20:25

Instead of using a UIScrollViewDelegate to correct the already wrong contentOffset (which will result in a jittery behaviour) you may want to consider to sub class UIScrollView instead and overriding setContentOffset:

- (void)setContentOffset:(CGPoint)contentOffset {
    if (contentOffset.y <= 60) {
        [super setContentOffset:contentOffset];
    }
}

Off course this can be generalized by adding a property for the min or max allowed value for the content offset. You may need to override setContentOffset:animated: as well.

查看更多
再贱就再见
4楼-- · 2019-01-21 20:27

It's possible to remove scrolling in vertical direction by setting the scrollView.contentSize height to the same value as scrollView.frame.size.height. Any overflowing content will be hidden. Same can of course be done to restrict vertical scrolling.

查看更多
登录 后发表回答