Search code examples
iosswiftbuttonuicollectionviewcell

How to select button in UICollectionViewCell and retrieve state for another action in swift?


I have two buttons in a uicollectioncell and want to select one and then perform an action on the other depending on the state of the first button. I have tried this but it throws up : "swift fatal error: unexpectedly found nil while unwrapping an Optional value"

func firstAction(sender:UIButton) {
    var cell = Customcell()
    cell.firstButton.selected = true
    cell.firstButton.selected = !cell.firstButton.selected
}

@IBAction func secondAction(sender: UIBarButtonItem) {
    var cell = CustomCell()
    if cell.firstButton.selected == true {
        // DO stuff....
    } else {
        println("No button selected")
    }
}

I set the button in cellForItemAtIndexPath like this:

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomCell
cell.firstButton.addTarget(self, action: "firstAction:", forControlEvents: UIControlEvents.TouchUpInside)
cell.secondButton.addTarget(self, action: "secondAction:", forControlEvents: UIControlEvents.TouchUpInside)

How can I fix this?


Solution

  • In your action methods you create new instances of CustomCell instead of referencing to the cell which holds the buttons. Try this code:

    func buttonAction (sender: UIButton) {
        var cell = sender as UIView
        while (!cell.isKindOfClass(UITableViewCell)) {
            cell = cell.superview!
        }
    
        if sender == cell.firstButton {
            // Do something when the first button was touched
        } else if sender == cell.secondButton {
            // Do something when the second button was touched
        }
    }
    

    Add this function as the action for both buttons.