Search code examples
iosswiftresetuicollectionviewcellselected

How to stop a variable from resetting when a cell is selected in a UICollectionView?


I am trying to create a matching game using a UICollectionView. I have a method for a UICollectionView with some properties:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    var definitionSelectedText:String = "None"
    var boatTypeSelectedText:String = "None"
    if cellSelected == false {
        if indexPath.item < 7 {
            definitionSelectedText = definitions[indexPath.item]
            println(definitionSelectedText)
            println(boatTypeSelectedText)
        } else if indexPath.item > 6 {
            boatTypeSelectedText = boatTypes[indexPath.item - 7]
            println(definitionSelectedText)
            println(boatTypeSelectedText)
        }
        cellSelected = true

I also have this method:

switch indexPath.item {
        case 7:
            switch definitionSelectedText {
            case "Used to carry the pharoah":
                if boatTypeSelectedText == "Royal Boat" {
                    if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
                        cellTitle.hidden = true
                        cell.backgroundColor = UIColor.greenColor()
                    }
               }

The problem that's happening is that definitionSelectedText resets to "None" when indexPath.item 7 is selected or any other ones. How can I prevent definitionSelectedText from resetting to "None" when an indexPath.item < 6 is selected? I appreciate any support!


Solution

  • You set definitionSelectedText to 'None' at the start of the function. The defintionSelectedText is only set to something else when the indexPath is less than 7, so naturally, when indexPath==7 it won't be changed. 7 is not less than 7.