Search code examples
iosswiftuicollectionviewtvosuipangesturerecognizer

How to override the handlePan selector in UICollectionView


In my tvOS app, I am trying to listen to changes in scrolling of my UICollectionView. After research, I found that the collection view natively receives a few gesture recognizers among them a UIPanGestureRecognizer with the selector handlePan:

<UIScrollViewPanGestureRecognizer: 0x101a4c1a0; state = Possible; delaysTouchesEnded = NO; view = <UICollectionView 0x1020c5d00>; target= <(action=handlePan:, target=<UICollectionView 0x1020c5d00>)>>

in the log, or in code:

myCollectionView.panGestureRecognizer

I was wondering if there's a way to add my controller as the target of the gesture recognizer, or maybe override the handlePan method. I tried implementing the UIGestureRecognizerDelegate but it does not give me an access to the handlePan method. Maybe I should just add a custom UIPanGestureRecognizer of my own on the collection view?


Solution

  • UICollectionView is a subclass of UIScrollView so you can detect scroll changes on collectionview by adding scrollview delegates.

    Objective-C

    // called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    }
    
    // called when scroll view grinds to a halt
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    }
    

    Swift

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    
    }