Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS separate scrollView & collectionView delegates into individual files

I have a UICollectionView and want to be able to perform custom behaviour when the user scrolls through implementing the scrollView delegate methods. Is it possible to have two separate objects that act as the collectionView delegate and scrollView delegate when working with a collectionView?

like image 451
agandi Avatar asked Mar 14 '23 19:03

agandi


1 Answers

You cannot have separate delegates. UICollectionView is a subclass of UIScrollView, and overrides its delegate property to change its type to UICollectionViewDelegate (which is a subtype of UIScrollViewDelegate). So you can only assign one delegate to a collection view, and it may implement any combination of UICollectionViewDelegate methods and UIScrollViewDelegate methods.

However, you can forward the UIScrollViewDelegate methods to another object without much difficulty. Here's how you'd do it in Swift; it would be very similar in Objective-C (since this is all done using the Objective-C runtime):

import UIKit
import ObjectiveC

class ViewController: UICollectionViewController {

    let scrollViewDelegate = MyScrollViewDelegate()

    override func respondsToSelector(aSelector: Selector) -> Bool {
        if protocol_getMethodDescription(UIScrollViewDelegate.self, aSelector, false, true).types != nil || protocol_getMethodDescription(UIScrollViewDelegate.self, aSelector, true, true).types != nil {
            return scrollViewDelegate.respondsToSelector(aSelector)
        } else {
            return super.respondsToSelector(aSelector)
        }
    }

    override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? {
        if protocol_getMethodDescription(UIScrollViewDelegate.self, aSelector, false, true).types != nil || protocol_getMethodDescription(UIScrollViewDelegate.self, aSelector, true, true).types != nil {
            return scrollViewDelegate
        } else {
            return nil
        }
    }

Note that MyScrollViewDelegate probably has to be a subclass of NSObject for this to work.

like image 52
rob mayoff Avatar answered Apr 26 '23 05:04

rob mayoff