Check direction of scroll in UIScrollView

前端 未结 3 1975
盖世英雄少女心
盖世英雄少女心 2020-12-17 03:46

I am trying to implement the method scrollViewWillBeginDragging. When this method is called I check that the user has selected one of the buttons that are w

3条回答
  •  有刺的猬
    2020-12-17 04:37

    You can keep a starting offset as a member of your class which you store when the delegate receives the scrollViewDidBeginDragging: message. Once you have that value you can compare the x value of the scroll view offset with the one you have stored and see whether the view was dragged left or right.

    If changing direction mid-drag is important, you can reset your compared point in the viewDidScroll: delegate method. So a more complete solution would store both the last detected direction and the base offset point and update the state every time a reasonable distance has been dragged.

    - (void) scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat distance = lastScrollPoint.x - scrollView.contentOffset.x;
        NSInteger direction = distance > 0 ? 1 : -1;
        if (abs(distance) > kReasonableDistance && direction != lastDirection) {
            lastDirection = direction;
            lastScrollPoint = scrollView.contentOffset;
        }
    }
    

    The 'reasonable distance' is whatever you need to prevent the scrolling direction to flip between left and right to easily but about 10 points should be about enough.

提交回复
热议问题