1

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.

2
  • 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 Commented Apr 14, 2017 at 10:47
  • In your storyboard, have you linked your collection view to the collectionView var you mentioned? This var should be marked as a @IBOutlet. Commented Apr 14, 2017 at 10:56

1 Answer 1

1

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) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.