Search code examples
iosiphoneswiftibaction

Multiple buttons to single IBAction - How to change background of the previous tapped button?


I have a group of buttons a user can tap, almost like a calculator.

The app will collect a series of 2 buttons taps. This is to select a card from a deck. 1st tap would be Ace through King. 2nd tap would be a suit.

When the 1st button is tapped, it will change the background to yellow (the rank). When the 2nd button is tapped, it will save the 2 selections as a pair and append to a string (the suit).

Once the 2nd button is tapped, I want to change the 1st tapped button back to blue.

With all my buttons linked to a single IBAction 'buttonTapped', I can't get it to change the 1st button background to blue, when tapping the 2nd button. (I would even be OK with the 2nd button changing ALL buttons linked to this IBAction to blue)

@IBAction func buttonTapped(theButton: UIButton) {

    var buttonDump = theButton.titleLabel!.text!
    var firstChar = Array(buttonDump)[0]

    if firstChar == "♠️" || firstChar == "♥️" || firstChar == "♦️" || firstChar == "♣️" {
    // MUST BE THE 2nd TAP, SO LETS CHANGE THE 1st TAPPED BG BACK TO BLUE
        self.n2.text = buttonDump
        theButton.backgroundColor = UIColor.blueColor()

    } else {

        self.n1.text = buttonDump
        theButton.backgroundColor = UIColor.yellowColor()
    }

Solution

  • The theButton parameter is the button that was tapped by the user. Basically the button that you change the background to yellow, you will need to keep a reference to this button, and then set it to blue when the second button is tapped.

    Something like this:

    var firstButton: UIButton?
    
    @IBAction func buttonTapped(theButton: UIButton) {
    
        var buttonDump = theButton.titleLabel!.text!
        var firstChar = Array(buttonDump)[0]
    
        if firstChar == "♠️" || firstChar == "♥️" || firstChar == "♦️" || firstChar == "♣️" {
            // MUST BE THE 2nd TAP, SO LETS CHANGE THE 1st TAPPED BG BACK TO BLUE
            //self.n2.text = buttonDump
    
            // Change first button to blue
            if( self.firstButton != nil ) {
                self.firstButton!.backgroundColor = UIColor.blueColor()
            }
        } else {
            //self.n1.text = buttonDump
    
            // Keep reference to first button
            self.firstButton = theButton
            self.firstButton!.backgroundColor = UIColor.yellowColor()
        }
    }