0

I want to implement UICollectionView with custom cells, and previously I have:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout 

and inside I implemented

func numberOfSections(in collectionView: UICollectionView) -> Int func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

and it's working fine. Now I want to implement more functions related to cell selection, but I also want to conform to MVC pattern so I'm trying to move the UICollectionView implementation to another file. Then I have:

class ViewController: UIViewController { @IBoutlet var grid: UICollectionView! ovverride func viewDidLoad() { ... grid = GridView(grid.frame, GridLayout()) //GridLayout() is the layout file working fine } } 

and another file:

class GridView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int {} func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {} func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {} } 

But then if running it'll give error:

collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 

I checked the link here: error, and tried to do this in the ViewController:

grid.dataSource = grid as! UICollectionViewDataSource? grid.delegate = grid as! UICollectionViewDelegate? 

But it's not working. May I know how to fix this?

EDIT Class AppDelegate gives the error. And I've also tried to set the initializer of GridView:

override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(...) self.dataSource = self self.delegate = self } 

But it's not working.

1
  • Check your model array not nil Commented Jan 27, 2017 at 7:35

2 Answers 2

2

You should try setting the datasource and delegate of GridView inside the initialiser (frame:, layout:) of GridView class.

override init(...) { super.init(...) self.dataSource = self self.delegate = self } 

And can you please mention the exact line that is giving the error? Maybe you are still using some UICollectionView related code in your ViewController?

Sign up to request clarification or add additional context in comments.

Comments

-1

Are you tried;

grid.dataSource = self grid.delegate = self 

If it works, after this you can customize your collection views by using tags in same delegate and data source functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.