Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable all buttons when one gets pressed in XCode?

Tags:

xcode

ios

swift

How do I make it so that when I press one button in XCode, the rest of the buttons (including the one that was pressed) become disabled? Of course I still want the function to be carried out by the button that gets pressed. I just don't want the users to be able to press any button more than once, nor do I want them to be able to press another button after they've already pressed a first one. Below are my IBActions for my two buttons in this case:

@IBAction func addVote1(sender: AnyObject) {

    var query = PFQuery(className: "VoteCount")
    query.getObjectInBackgroundWithId("BiEM17uUYT") {
        (voteCount1: PFObject!, error: NSError!) ->Void in
        if error != nil {
            NSLog("%@", error)
        } else {
            voteCount1.incrementKey("votes")
            voteCount1.saveInBackgroundWithTarget(nil, selector: nil)
        }

        let votes = voteCount1["votes"] as Int
        let votes2 = voteCount1["votes2"] as Int
        self.pollResults1.text = "\(votes) votes                 \(votes2) votes"
        }
    }

@IBAction func addVote2(sender: AnyObject) {

    var query = PFQuery(className: "VoteCount")
    query.getObjectInBackgroundWithId("BiEM17uUYT") {
        (voteCount1: PFObject!, error: NSError!) -> Void in
        if error != nil {
            NSLog("%@", error)
        } else {
            voteCount1.incrementKey("votes2")
            voteCount1.saveInBackgroundWithTarget(nil, selector: nil)
        }

        let votes = voteCount1["votes"] as Int
        let votes2 = voteCount1["votes2"] as Int
        self.pollResults2.text = "\(votes) votes                 \(votes2) votes"
        }
    }
}
like image 340
ansariha Avatar asked Dec 20 '22 09:12

ansariha


1 Answers

Set up @IBOutlet properties for the buttons if you haven't already, then add a lazy var array of the buttons. In the button handler, set each button's enabled property to false.

class ViewController {
    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!

    lazy var buttons: [UIButton] = [self.button1, self.button2]

    // ...

    @IBAction func addVote1(sender: AnyObject) {
        for button in self.buttons {
            button.enabled = false
        }
        // ...
    }
}
like image 95
Nate Cook Avatar answered Dec 24 '22 01:12

Nate Cook