i am trying to add a TableView inside UICollectionViewCell, so i want to manage that cell by myself from TableView. So to be more clear, if indexPath.row is 2, then i want to call my tableView cell's inside collectionview indexPath.row.
Please check the picture, i have made with red colour what i want to do. I created everything programmatically, using UICollectionViewController and UICollectionViewControllerFlowLayout.
In the above diagram view controller which holds the tableview and its cell holds collection view. Well as we see in the diagram, tableview cell acts as a datasource and delegate for respective collection view that is present in the tableview cell. Each collection view asks tableview cell to provide data to be shown in the collection view.
UICollectionView programmatically Creating collection view controllers using only Swift code requires only a few additional lines. You can implement loadView and create your UICollectionView object there. Store a weak reference of it inside the controller, and the rest is the same.
Well as we see in the diagram, tableview cell acts as a datasource and delegate for respective collection view that is present in the tableview cell. Each collection view asks tableview cell to provide data to be shown in the collection view.
If you'd like to add views to your cell, you should use the init (frame:) method, and set up your view hierarchy there. Instead of awakeFromNib you should style your views in the init method as well.
For those who need it, i found the solution:
class CustomizedCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate {
var tableView = UITableView()
let cellIdentifier: String = "tableCell"
override func layoutSubviews() {
super.layoutSubviews()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier)
cell.textLabel?.text = "1 CUP"
cell.detailTextLabel?.text = "Whole"
return cell
}
}
Then at viewDidLoad method at CollectionView i did this:
collectionView?.register(CustomizedCell.self, forCellWithReuseIdentifier: "cell")
And after that i have called like this at cellForRowAt indexPath method of UICollectionView:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomizedCell
return cell
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With