Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Swift 2.0 Buttons, How do i make it so i know how many times that button has been pressed?

I need a button(button1) that has a while loop inside of it that only works when another button(button2) hasn't been pressed and the first button(button1) been pressed once, so if it the (button1) was pressed once the while loop will work every time after that.

1 Answer

Hi Shane,

This should actually be pretty easy. If you boil it down, you only need to track two things: Has Button1 been pressed? and Has Button2 been pressed? If I'm understanding you correctly, Button1 shouldn't work the first time it's pressed no matter what. After that, Button1 should only work if Button2 has not been pressed.

Since we need to keep track of the answer to two Yes/No questions, let's set up two boolean properties on our view controller:

class ShanesTerrifficViewController {
  var button1HasBeenPressed = false
  var button2HasBeenPressed = false
}

Then inside the @IBAction that gets called when each button is pressed, have a check:

class ShanesTerrifficViewController {
  var button1HasBeenPressed = false
  var button2HasBeenPressed = false

  @IBAction button1Pressed(sender: UIButton) {
    if !button1HasBeenPressed {  // if it hasn't been pressed
      button1HasBeenPressed = true  // well, we just pressed it, so...
    } else if !button2HasBeenPressed { // OK Button1 has been and Button2 hasn't. Proceed.
      // do cool stuff
    }

  @IBAction button2Pressed(sender: UIButton) {
    if !button2HasBeenPressed {  // if it hasn't been pressed
      button2HasBeenPressed = true  // well, we just pressed it, so...
    }
    // not sure what you want to do with button2, but do it here
  }
}

Does that make sense? All we're doing is storing "state" in properties. If you wanted to get fancier, you could do something like create an extension of UIButton, and add a property to it called hasBeenPressed or something, and then you'd be doing cool checks like:

if button1.hasBeenPressed {
// ... //

Which is probably a better way to go if you're doing this kind of thing a lot.

I hope this helps! Let me know if I can clarify anything. Also, I typed this all right in the editor here, so no compiler help - very possible there are typos etc. The concept is the important part, though.

Cheers :beers:

-Greg