Here is the solution for swift.
you need to setup a collectionview data source and delegate into the tableview cell using tableView delegation method cellForRowAtIndexPath, after this use a collectionview datasource and delegate method into a viewController where you have confirmed tableveiew data source and delegate. Here is the code for mainViewController:
extension MainViewController:UITableViewDataSource, UITableViewDelegate {
// .....do some table view setup like numberOfRowsInSection ......
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("yourReusecellIdentifier", forIndexPath: indexPath) as! yourCustomCell
cell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
return cell
}
}
Here cell.setcollectionViewDataSourceDelegate(self, forRow:indexPath.rom) code sets a collectionview delegate and datasource into table view cell after this drag the collectionview outlet to tableview cell. Into the tableView cell add a mehod setcollectionViewDataSourceDelegate to set collectionView delegate as follow :
class yourCustomCell: UITableViewCell {
//MARK:- Properties
@IBOutlet weak var collectionView: UICollectionView!
//MARK:- initialization methods
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK:- Setup collectionView datasource and delegate
func setCollectionViewDataSourceDelegate
<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(dataSourceDelegate: D, forRow row: Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()
}
}
After this use the collection view delegate method into you view controller:
extension MainViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionViewReuseIdentifier", forIndexPath: indexPath) as! YourCollectionViewCustomCell
.......cell configure....
return cell
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("get selected collectionview itemindex \(indexPath.row)")
}
}
For clear explanation visit this https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/