2

I want to swizzle some scrollview methods for my collection/tableview to track some events. I am getting errors as it is not able to find scrollViewDidScroll: Method in collectionview. I tried to use below code

extension UICollectionView
{

    public override class func initialize() {
        struct Static {
            static var token: dispatch_once_t = 0
        }

        // make sure this isn't a subclass
        if self !== UICollectionView.self {
            return
        }

        dispatch_once(&Static.token) {
            let originalSelector = #selector(self.scrollViewDidScroll(_:))
            let swizzledSelector = #selector(self.sp_scrollViewDidScroll(_:))

            let originalMethod = class_getInstanceMethod(self, originalSelector)
            let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)

            let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

            if didAddMethod {
                class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod)
            }
        }
    }

    // MARK: - Method Swizzling

    func sp_scrollViewDidScroll(scrollView:UIScrollView) {
        self.sp_scrollViewDidScroll(animated)
        print("Swizzled sp_scrollViewDidScroll in place of scrollViewDidScroll")
    }
}

Error: Type UICollectionView has no member 'scrollViewDidScroll'

Gavin
  • 8,204
  • 3
  • 32
  • 42
Jasveer Singh
  • 354
  • 3
  • 10

1 Answers1

1

I think you find that method in UIScrollViewDelegate protocol, not in the class itself. Implement it in your collectionView's delegate (UICollectionViewDelegate extends UIScrollViewDelegate) . Best

Jef
  • 4,728
  • 2
  • 25
  • 33
  • is there a way to swizzle delegate methods ? – Jasveer Singh Apr 06 '16 at 15:42
  • They're like any other method, so yes... But because this uses delegation to offload the implementation to the class/object of your choice the idea of swapping implementations out is entirely redundant, just implement it how you need it done in your delegate and viola. – Jef Apr 06 '16 at 20:38