[英]Get values of cell collectionView when not are visible cells
我想在我的集合视图中获取所有单元格的值,但是我有不同的部分,我的集合视图不是所有单元格都可见,当我尝试获取值时,单元格可见获取值成功但当我尝试获取值时其余单元格显示错误:
unexpectedly found nil while unwrapping an Optional value
我的代码是
func getValueCells() {
for section in 0..<numberOfYears {
for row in 0..<3 {
let index = IndexPath(row: row, section: section)
let cell = myCollection!.cellForItem(at: index) as! CircularCell
print(cell.lblPercent.text)
}
}
}
索引是对的,有什么帮助吗?
if let cell = myCollection!.dataSource?.collectionView(self.collectionView, cellForItemAt: index) as? CircularCell {
//access cell here
}
CollectionView将无法返回不在可见范围内的单元格,因为单元格可能已被重用。
您应该向数据源询问单元格而不是collectionView本身。
希望能帮助到你
编辑:
虽然上面的答案解释了如何访问可见indexPath之外的单元格,但您的代码仍然无法正常工作
print(cell.lblPercent.text)
除非您已实现,否则您将无法访问单元格内的label / textField的内容
override func prepareForReuse() {
//save the labels text somewhere in a variable or model
}
在CircularCell
,确保使用已实现的cellForRowAtIndexPath
文本初始化所有标签/ textFields。
重复使用单元格时,单元格内UI元素的值不会保留。 它的责任是确保同样的
由于UICollectionView
和UITableView
单元格的可重用行为无法获取不可见单元格的值,
因为,当细胞变得不可见时,它们将失去参考。
您可以从上面的答案中获取可见单元格中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.