1
votes

I have a view controller which contains collection view. Collection view's delegate and datasource are one custom class and I can't access Collection View itself from that class. The class includes UICollectionViewFlowLayout, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource.

I tried accessing the collection view by typing self.collectionView which didn't work, saying: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)".

Tried setting a static let variable which points to View Controller containing collection view but it also didn't work.

1
You should keep delegate and datasource method in your viewcontroller, but keep all data of them in the other class and return it in your viewcontroller delegate method - Tj3n
In your storyboard, have you linked your collection view to the collectionView var you mentioned? This var should be marked as a @IBOutlet. - Paulo Mattos

1 Answers

1
votes

Delegates and datasources are dataprovider, not more. Extracting them into own classes is a very good idea (object oriented design). But these classes shouldn't implement more than the api of the protocol and maybe some private helper functions for them. Each protocol function provide access to your collection view by giving a reference as the first parameter.

e.g.

func numberOfSections(in: UICollectionView)