首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >1节和2个细胞,但4个indexPath.row

1节和2个细胞,但4个indexPath.row
EN

Stack Overflow用户
提问于 2018-05-01 11:21:40
回答 1查看 270关注 0票数 1

Swift 4.我想在一个部分返回两个单元格,所以在我的类CollectionViewController中:

代码语言:javascript
运行
复制
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,因为我在一个部分中只有两个单元格?

代码语言:javascript
运行
复制
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
    print(indexPath.row)
    return cell 
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-01 11:51:19

cellForItemAt被打了四次电话。当视图加载时,numberOfItemsInSection会被调用两次(每个单元格调用一次)。当您从reloadData()闭包调用DispatchQueue.main.async时,它将再次被调用两次。

更新--如何避免第一次调用:

您需要将单元格数据存储在数组中,并且只需要在调用reloadData()之前填充该数组。因此,当第一次加载视图时,数组将为空。

代码语言:javascript
运行
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50115607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档