Detect if UIScrollView is scrolling

前端 未结 4 754
面向向阳花
面向向阳花 2021-02-01 07:21

I\'m looking to detect if (not when) a UIScrollView is scrolling.

i.e.

BOOL isScrolling = myscrollview.scrolling;

How woul

相关标签:
4条回答
  • 2021-02-01 07:24
    - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;
    

    use a flag to save current scroll status? it could only solve the setContentOffset:animated: problem.

    The "scrolling" is just an effect, there are many ways that make a scrollview "scrolling", e.g. set the content offset continuously. So there should be NO answer for this question.

    0 讨论(0)
  • 2021-02-01 07:30

    I usually do this by setting a boolean variable in the scrollViewWillBeginDragging: and scrollViewDidEndDragging:willDecelerate: events.

    UIScrollView Docs

    0 讨论(0)
  • 2021-02-01 07:37

    This may be a slightly dodgy way of doing it, but I've used it in my code before and it hasn't failed me yet. :)

    Swift

    let isScrolling = scrollView.layer.animation(forKey: "bounds") != nil
    

    Objective-C

    BOOL isScrolling = [scrollView.layer animationForKey:@"bounds"] != nil;
    

    In addition to self.contentOffset the offset of a UIScrollView is stored in the bounds.origin property of the UIView as well (I guess since it's a bit more convenient in lower-level code). When you call [setContentOffset:animated:], it's passing that off to the UIScrollView as a CABasicAnimation, manipulating the bounds property.

    Granted, this check will also return true if the shape of the scroll view itself is animating. In which case you may need to actually pull the bounds object out of the animation ([CAAnimation toValue]) and do a manual compare to see if origin itself is changing at all.

    It's not the most elegant solution, but I like being able to avoid having to make use of the scroll view delegate whenever possible. Especially if the scroll view in question might be a subclass explicitly vending its delegate as part of its public API. :)

    0 讨论(0)
  • 2021-02-01 07:40

    Not a very clean solution .. but should be the most reliable:

    var isScrolling = false
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isScrolling = true
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate { scrollViewDidEndScrolling(scrollView) }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScrolling(scrollView)
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        scrollViewDidEndScrolling(scrollView)
    }
    
    func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {
        isScrolling = false
    }
    
    0 讨论(0)
提交回复
热议问题