Swift 4.我想在一个部分返回两个单元格,所以在我的类CollectionViewController中:
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1 }
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2 }我看到两个单元格,但是如果我在下面的代码中打印indexPath.row (仍然在同一个类中),就会看到0 1 0 1。为什么它不仅仅是一个0 1,因为我在一个部分中只有两个单元格?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
print(indexPath.row)
return cell
}发布于 2018-05-01 11:51:19
cellForItemAt被打了四次电话。当视图加载时,numberOfItemsInSection会被调用两次(每个单元格调用一次)。当您从reloadData()闭包调用DispatchQueue.main.async时,它将再次被调用两次。
更新--如何避免第一次调用:
您需要将单元格数据存储在数组中,并且只需要在调用reloadData()之前填充该数组。因此,当第一次加载视图时,数组将为空。
var yourArray = [YourObject]() //Empty Array
//..
DispatchQueue.main.async {
//append your two items to the yourArray
yourArray.append(/*cell1data*/)
yourArray.append(/*cell2data*/)
self.collectionView?.reloadData()
}
//..
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return yourArray.count
}https://stackoverflow.com/questions/50115607
复制相似问题