我确信这个问题在某处已经有了答案,但既然我找不到答案,我就在这里给出一个答案。
您的错误在这里:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/...
let myCellImage = UIImage(named: images[indexPath.row]) //<< indexPath.row will return 0,1 and 2 for each of your collection view
/...
}
表视图中的每个集合视图
没有
相互沟通,形成更大的集体观点。由于所有的都为numberOfItemsInSection提供了3的int值,并且它们的numberOfSections默认为1(您没有设置任何值),因此在尝试填充数据时,它们中的每一个都将在indexpath(0,0)、(0,1)和(0,2)处请求项。
但是,您的硬编码数组是一个包含30项的数组。因此,当请求cellForItemAt时,每个集合视图对于图像[indexPath.row]只会得到0、1和2。还应该使用indexPath。集合视图的项,indexPath。行用于表视图,如果使用错误,它可能工作,也可能不工作。
解决方案
您只需设置
tag
要标记其行的集合视图的属性:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/...
//Make sure you have a subclass for UITableViewCell that have an IBOutlet that connects to the collection view
cell.collectionView.tag = indexPath.row //Note that this only works in your situation where the table view have only 1 section.
/...
}
然后将阵列拆分为二维阵列:
var images = [
["11.png", "12.png", "13.png"],
["21.png", "22.png", "23.png"],
["31.png", "32.png", "33.png"],
["41.png", "42.png", "43.png"],
["51.png", "52.png", "53.png"],
["61.png", "62.png", "63.png"],
["71.png", "72.png", "73.png"],
["81.png", "82.png", "83.png"],
["91.png", "92.png", "93.png"],
["101.png", "102.png", "103.png"]
]
最后在集合视图中读取数组,如下所示:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/...
let myCellImage = UIImage(named: images[myCell.tag][indexPath.item])
/...
}