dimanche 26 avril 2015

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()
    }

Thanks for supporting a Swift n00b, I'm working on it!

--UPDATE--

It makes sense that I need to define 'firstButton' in the class buttonTapped belongs to. I'm struggling here, I've attempted defining it as a UIButton so it is ready to receive the sender information.. What's the trick?

//What is the proper way to define a 'empty' UIButton before the value can be sent from the buttonTapped function?

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
        self.firstButton.backgroundColor = UIColor.blueColor()
    } else {
        self.n1.text = buttonDump

        // Keep reference to first button
        self.firstButton = theButton
        self.firstButton.backgroundColor = UIColor.yellowColor()
    }


Aucun commentaire:

Enregistrer un commentaire