Reputation: 2418
Is it possible to select a row or a section of a uitableview / uicollection views label is equal to a particular string.
so as an example
let array = ["a","b","c","d","e"]
cell.textlabel.text = array[indexPath.row]
I then select rows 0,1,4 and add them to a saved array
let savedArray = ["a", "b", "e"]
I know I could save the indexPath and add it to a dictionary and then call it that way but what if the array changes to
let array = ["a","f","b","c","d","e"]
I would then not be selecting the right rows.
Thus what I want to do is search the cells.titleLabels.text and if it matches then programatically select it.
so my question is how do I search the cells.titleLabel?
thanks in advance
Upvotes: 0
Views: 713
Reputation: 72450
You can compare the object value in cellForItemAt
method.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
cell.textlabel.text = array[indexPath.row]
cell.isSelected = savedArray.contains(array[indexPath.row])
return cell
}
Upvotes: 2
Reputation: 424
In your cellForIndexAt:
CollectionView delegate method (where you set up the cell) you can set a condition to check if the current data item for the given cell is in your savedArray
- and if so, you can the set the selected state for that cell.
so something like:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
// iterate through saved array and see if your current item is in it
let savedItems = savedArray.Filter({ item -> Bool in
return item == array[indexPath.row] // this shall return true if item for current cell is in the saved array OR you could do any kind of logical comparison here e.g. item == "random string"
})
if(savedItems.count > 0) {
// here set the selected state of cell as you wish
}
return cell
}
Hope this helps.
Upvotes: -1