One fantastic way to Load ‘CollectionView’ inside ‘TableViewCell’ using Two ‘Extensions’ in swift3, iOS

As We know we, Often, we assign a collection view’s data source to its view controller. But here the problem is that we have only one view controller and many collection views.

As I have taken number of ‘Sections’ inside table view. so following is the Solution to distinguish between a collection view on the first section , and one on the second , third and fourth…

So here is a way to store which table view cell a collection view is in.

 

  • TableView : I have taken multiple sections And Only One Row.
  • Collection View : I have Only one Section And Multiple Items.

 

In ViewController.swift Use Following –

  • Extension :

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {

     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int   {

          return 3

     }

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell   {

          let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “UploadCell”, for: indexPath) as!                 UploadCollectionViewCell

          //Code

    return cell

     }

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath  {       

          print(“Collection view at row \(collectionView.tag) selected index path \(indexPath)”)

     }

}

 

 

In TableViewCell.swift Use Following –

  • Extension :

  extension TableViewCell  {

          func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {

               collectionView.delegate = dataSourceDelegate

               collectionView.dataSource = dataSourceDelegate

               collectionView.tag = row

               collectionView.setContentOffset(collectionView.contentOffset, animated:false) // Stops collection view if it was scrolling.

               collectionView.reloadData()

          }

          var collectionViewOffset: CGFloat {

               set { collectionView.contentOffset.x = newValue }

               get { return collectionView.contentOffset.x }

          }

     }

 

*******  One IMP addition in ‘willDisplay’ method of tableView in ViewController.swift  *******

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

          guard let tableViewCell = cell  else { return }

          tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.section)

     }

 

 

Thanks.