我有一个相当大的应用程序,它有很多集合视图.大多数集合视图都具有相同的数据源和流布局代表(相同的大小,边距等)的实现.我正在尝试创建一个提供UICollectionViewDataSource和UICollectionViewDelegateFlowLayout的默认实现的协议.这是我的代码.
protocol TiledCollectionView{} extension UICollectionViewDataSource where Self: TiledCollectionView{ //default implementation of the 3 methods to load the data ... } extension UICollectionViewDelegateFlowLayout where Self: TiledCollectionView { //default implementation for layout methods to set default margins etc... } class MyViewController: UIViewController,TiledCollectionView,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ // the rest of the required logic for view controller // here I Don't implement any CollectionView methods since I have provided the default implementation already }
问题是,编译器抱怨MyViewController不符合UICollectionViewDataSource.这不应该是这种情况,因为我清楚地说,如果类型是TiledCollectionView,则添加默认实现.@H_403_4@
有人可以帮忙吗?@H_403_4@
我知道这不完全是你问的,我试过 – 它没用.现在寻找可能的答案,因为有类似的情况.但我可以为您提供如何选择如何在自定义协议中隐藏委托/数据源实现的所有逻辑.
class CollectionViewProtocolHandler: NSObject,UICollectionViewDelegate,UICollectionViewDataSource { func collectionView(collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int { return 0 } func collectionView(collectionView: UICollectionView,cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return UICollectionViewCell() // only for test } } protocol CollectionViewProtocol { var handler: CollectionViewProtocolHandler! {get set} mutating func useProtocolForCollectionView(collectionView: UICollectionView) } extension CollectionViewProtocol { mutating func useProtocolForCollectionView(collectionView: UICollectionView) { handler = CollectionViewProtocolHandler() collectionView.delegate = handler collectionView.dataSource = handler } } class ViewController: UIViewController,CollectionViewProtocol { var handler: CollectionViewProtocolHandler! // CollectionViewProtocol convenience override func viewDidLoad() { super.viewDidLoad() let collectionView = UICollectionView(frame: view.bounds,collectionViewLayout: UICollectionViewFlowLayout()) collectionView.backgroundColor = .redColor() view.addSubview(collectionView) var reference = self reference.useProtocolForCollectionView(collectionView) // for initialize protocol } }