简体   繁体   中英

Get values of cell collectionView when not are visible cells

I want get values of all cells in my collection view but I have differents sections and my collection view is it not so all cells visible , when I try obtain the values , the cell visible obtain values with success but when I try obtain the values for the rest cells show the error:

unexpectedly found nil while unwrapping an Optional value

My code is

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)
        }
    }
}

The index is correct , any help?

if let cell = myCollection!.dataSource?.collectionView(self.collectionView, cellForItemAt: index) as? CircularCell {
  //access cell here
}

CollectionView will not be able to return the cell which is not in visible range as the cell might have been reused.

You should ask the data source for the cell rather than collectionView itself.

Hope it helps

EDIT:

Though above answer explains how to get the access to the cell which is outside the visible indexPath your code still will not work

print(cell.lblPercent.text)

You will not be able to access the content of label/textField which is inside the cell unless u have implemented

override func prepareForReuse() {
   //save the labels text somewhere in a variable or model
}

in CircularCell and made sure u initialize all the labels/textFields with text in cellForRowAtIndexPath you have implemented.

Values of the UI elements inside the cell are not persisted when cell gets reused. Its ur responsibility to ensure the same

Due to the reusable behavior of UICollectionView and UITableView cells that is not possible to get the values of invisible cells,

Because, the cells will lose their reference whenever it becomes invisible.

You can get the values from the visible cell like above answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM