To fully answer the question, I added a tableView with 2 rows, each containing a CollectionView.
It still works OK, even at first scroll, as the screen capture illustrates:
Code for creating the collections:
import UIKit
class TestViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var collection1: UICollectionView!
@IBOutlet weak var collection2: UICollectionView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellItemForCollection", for: indexPath)
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 50, height: 50)
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 260, height: 120), collectionViewLayout: layout)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
collectionView.backgroundColor = UIColor.clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.tag = 10 + indexPath.row // 10 or 11
cell.contentView.addSubview(collectionView)
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var id = ""
switch collectionView.tag {
case 1 : id = "Standard1"
case 2 : id = "Standard2"
case 10, 11: id = "MyCell"
default: break
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath)
for v in cell.contentView.subviews {
v.removeFromSuperview()
}
switch collectionView.tag {
case 1 : cell.backgroundColor = .red
case 2 : cell.backgroundColor = .systemYellow
case 10: cell.backgroundColor = .systemBlue
case 11: cell.backgroundColor = .systemGreen
default: break
}
let label = UITextView(frame: CGRect(x: 5, y: 4, width: 30, height: 20))
label.text = String(indexPath .row)
cell.contentView.addSubview(label)
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
collection1.tag = 1 // The top collections (out of TableView)
collection2.tag = 2
}
}