how to have 2 functions with one button

I was wondering how i could have 2 functions work from 1 button. One would happen on the first time you click and second will happen the second time you click. in java something like this:

if button pressed{
 // Code

if button pressed{
// Code

}

}

or at least that's how I was taught in java. so I'm wondering how I could do that in swift. Thanks!

Answered by szymczyk in 705940022

You need a Boolean variable that tells you whether or not to run the first function.

var shouldRunFirstFunction = true

When the button is pressed, check the value of the Boolean variable. If it's true, run the first function. If it's false, run the second function.

if buttonPressed {
    if shouldRunFirstFunction {
        firstFunction()
        shouldRunFirstFunction = false
    } else {
        secondFunction()
        shouldRunFirstFunction = true
    }
}

In a real app you should also change the button text after clicking the button to indicate you're doing something different each time you click the button. Otherwise people will be confused if clicking a button does one thing the first time and something else the second time.

Accepted Answer

You need a Boolean variable that tells you whether or not to run the first function.

var shouldRunFirstFunction = true

When the button is pressed, check the value of the Boolean variable. If it's true, run the first function. If it's false, run the second function.

if buttonPressed {
    if shouldRunFirstFunction {
        firstFunction()
        shouldRunFirstFunction = false
    } else {
        secondFunction()
        shouldRunFirstFunction = true
    }
}

In a real app you should also change the button text after clicking the button to indicate you're doing something different each time you click the button. Otherwise people will be confused if clicking a button does one thing the first time and something else the second time.

how to have 2 functions with one button
 
 
Q