如何为UICollectionView调配ScrollViewDidScroll或其他scrollview方法

时间:2016-04-06 14:25:17

标签: ios swift method-swizzling

我想为我的collection / tableview调整一些scrollview方法来跟踪一些事件。我收到错误,因为它无法在collectionview中找到scrollViewDidScroll:方法。我试着使用下面的代码

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")
    }
}
  

错误:类型UICollectionView没有成员' scrollViewDidScroll'

1 个答案:

答案 0 :(得分:1)

我认为您在UIScrollViewDelegate协议中找到了该方法,而不是在类本身中。在collectionView的委托中实现它(UICollectionViewDelegate扩展UIScrollViewDelegate)。最好