[英]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.