title: How to reuse a Collection View? -Swift
body: <p>In an application I'm trying to build I need a lot of <code>UICollectionView</code>s (around 10). I decided to make the <code>collectionView</code>s without the use of <em>Storyboards</em>   (i.e entirely in code) . <em>Storyboards</em> complicate things(for many collectionViews) .</p>
  
  <p>Here is the code: </p>
  
  <p><strong>I)</strong> </p>
  
  <pre><code>   override func viewDidLoad() {
  
      super.viewDidLoad()
          //Create the collection View      
  
      let frame =                  CGRect(origin: CGPoint.zero , size: CGSize(width: self.view.frame.width , height: 50))
      let layout =                 UICollectionViewFlowLayout()
       collectionView1 =           UICollectionView(frame: frame, collectionViewLayout: layout)
      collectionView1.dataSource = self
      collectionView1.delegate =   self
      collectionView1.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
      collectionView1.backgroundColor = UIColor.red
      view.addSubview(collectionView1) }
  </code></pre>
  
  <p><strong>II)</strong></p>
  
  <pre><code> // TheData Source and Delegate 
  
  extension ViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
  
  
  public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
  
   return 5
  
  }
  
  public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
  
  
          let cell =              collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
          cell.backgroundColor = UIColor.darkGray
          return cell
  
  }
  
  
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -&gt; CGSize {
  
      return CGSize(width: 50, height: 50)
  }
   }
  </code></pre>
  
  <p>This would create one <code>collectionView</code> in a View Controller , however if I had to create ten more of these I would have to rewrite the above code 10 times .</p>
  
  <p>So I tried to create a separate <code>MyCollectionView</code> class with the basic implementation needed to add a <code>collectionView</code> to a <code>ViewController</code> so that
   all I had to do in my view controller was something as simple as  </p>
  
  <pre><code> override func viewDidLoad() {
  
  super.viewDidLoad()
  
   let shoesCollection = MYCollectionView(frame : ...)
   self.view.addSubview(shoesCollection)   
  
   let foodCollection = MYCollectionView(frame : ...)
   self.view.addSubview(foodCollection)
  
   let carCollection = MYCollectionView(frame : ...)
   self.view.addSubview(carCollection)   
  
   }
  </code></pre>
  
  <p>or something similar . However I was unsuccessful. 
  How shall I go about this? Thanks!</p>