In my CollectionView
I want the user to select cells. If a cell is selected, an image should appear and the label should disappear. The User should also be able do deselect the cell again and then selecting it again (the selecting after deselecting doesn't work at the moment).
The text for the labels comes from an array and is shown properly.
But when selecting a cell, and then scrolling other cells are selected to. When scrolling up back again randomly other cells a selected that have never been touched. I think it has to do something with the reuse of the cell so I already added a prepareForReuse
Method in the Class of the cell.
I also want to store which cells were selected when the user closes the app and show them as selected when he opens it up again.
A further problem is, that I want it only to be possible to select a cell, when a certain other cell is also selected. What is the best way to do this?
class CollectionViewController: UICollectionViewController {
var array:[String] = []
var selectedIndexes:NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
doors = ["1","2","3"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:MyCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell
var Label = cell.viewWithTag(1) as! UILabel
Label.text = array[indexPath.row]
let keystring = String(format:"%i", indexPath.row)
if (self.selectedIndexes[keystring] != nil) {
cell.myLabel.hidden = true
cell.myImageView.image = UIImage(named:"1")!
}
else {
}
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let keystring = String(format:"%i", indexPath.row)
if (self.selectedIndexes[keystring] != nil) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
cell.myLabel.hidden = false
cell.myImageView.image = nil
}
else {
selectedIndexes.setObject(keystring, forKey: keystring)
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
cell.myLabel.hidden = true
cell.myImageView.image = UIImage(named:"1")!
}
The class of the CollectionViewCell:
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myImageView: UIImageView!
override func prepareForReuse() {
super.prepareForReuse()
self.myImageView.image = nil
self.myLabel.hidden = false