title: iOS: put UICollectionView in a separate class
body: <p>I want to implement UICollectionView with custom cells, and previously I have:</p>
  
  <pre><code>class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
  </code></pre>
  
  <p>and inside I implemented </p>
  
  <pre><code>func numberOfSections(in collectionView: UICollectionView) -&gt; Int
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>class ViewController: UIViewController {
      @IBoutlet var grid: UICollectionView!
      ovverride func viewDidLoad() {
          ...
          grid = GridView(grid.frame, GridLayout()) //GridLayout() is the layout file working fine
      }
   }
  </code></pre>
  
  <p>and another file:</p>
  
  <pre><code>class GridView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
      func numberOfSections(in collectionView: UICollectionView) -&gt; Int {}
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {}
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {}
  }
  </code></pre>
  
  <p>But then if running it'll give error: </p>
  
  <pre><code>collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance 
  </code></pre>
  
  <p>I checked the link here: <a href="https://stackoverflow.com/questions/31388118/connecting-a-collectionview-to-a-viewcontroller-getting-error-when-connecting-d">error</a>, and tried to do this in the ViewController:</p>
  
  <pre><code>grid.dataSource = grid as! UICollectionViewDataSource?
  grid.delegate = grid as! UICollectionViewDelegate?
  </code></pre>
  
  <p>But it's not working. May I know how to fix this?</p>
  
  <p><strong>EDIT</strong>
  Class AppDelegate gives the error. And I've also tried to set the initializer of GridView:</p>
  
  <pre><code>override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
      super.init(...)
      self.dataSource = self
      self.delegate = self
  }
  </code></pre>
  
  <p>But it's not working.</p>