I know that this topic has been discussed a lot on StackOverflow and am aware that a Collection View recycles its cells .
However, I have not found a suitable explanation for the problem I describe below.
In my app, I have a collection view that has multiple cell types in it - each cell only exists once in the collection view.
The collection view acts like a form in which the user can enter different things - split up on a few cells.
If I now scroll down, the first cell is not visible anymore. However, it is also not removed from the collection view as the entered data is still correctly displayed if I scroll back to the top.
If a user clicks a button, I am fetching every collection view cell from the collection view and run a validation method on it.
Just like the following:
let firstCell = myCollectionView.cellForItem(at: IndexPath(row: 0, section: 0)) as! DefaultElementCell // get the cell
firstCell.validateEntries() // validates entries and highlights incorrect fields
If I now scroll to the bottom of the collection view (the last cell), I get an error "unexpectedly found nil while unwrapping an optional value" . The optional value in this case is the Cell that should be returned by cellForItemAt() .
So, I think that the cell has already been removed but on the other hand the text entered into the fields and everything are still there if I scroll back to the first cell.
if let firstCell = myCollectionView.dataSource?.collectionView(self.myCollectionView, cellForItemAt: IndexPath(row: 0, section: 0)) {
print((firstCell as! DefaultElementCell).validateEntries()) // does nothing
}
Now, I don't get the error "unexpectedly found nil" anymore but validateEntries() also does nothing anymore.
Is there any way I can correctly get the invisible collection view cells or prevent the collection view from re-using cells? As already mentioned, every cell type only exists once in the collection view.
I would appreciate any help!
You need to create an array of same size as you number of cells then
var arr = [String]()
// inside cellForRowAt
cell.textfield.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControl.Event.editingChanged
cell.textfield.tag = indexPath.item
and
@objc func textFieldDidChange(_ textField: UITextField) {
arr[textfiled.tag] = textfield.text!
}
then validate you entry from arr
values
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.