One button for several actions - swift

I am having trouble configuring a button that:
1st press will do action 1
2nd press will do action 2
3rd press will do action 3
4th press will do action 1
5th press will do action 2
...and so on
Is there any way to configure that button?
Thanks

If you were interested in keeping track of the number of clicks while also doing the job of the 3 alternating tasks:
var counter : Int = 0
#IBAction func buttonClicked(_ sender: Any) {
counter+=1
//print(counter)
switch counter % 3 {
case 1:
// First Action
case 2:
// Second Action
default:
// Third Action
}
}

Do as below in your button action:
var counter = 0
#IBAction func buttonTapped(_ sender: Any) {
counter += 1
switch counter {
case 1:
// do your action
case 2:
// do your action
case 3:
// do your action
counter = 0
default:
break
}
}

Related

Swift, increment a number on each button tap

I have created an app where I am uploading data to a database. However, I want to assign a specific key to each entry. For example, if the user is making their first entry into db. The key name would be "Entry 1", if they make a second entry, it would be "Entry 2". This is what I tried, but its not working.
#IBAction func doSomething(_ sender: Any) {
var keyCounter = 0
keyCounter = keyCounter + 1
print("Key Counter = ",keyCounter)
}
Here is the output of me pressing the button 3 times. Expected output: Key Counter = 3
Actual output:
I know that whenever I press the button its re-initializing the value of the counter to 0. I am not sure what the best way to approach this is. Any guidance or help would be appreciated.
Do something like this:
class FooViewController: UIViewController {
var keyCounter = 0
#IBAction func doSomething(_ sender: Any) {
keyCounter = keyCounter + 1
print("Key Counter = ",keyCounter)
}
}

Calling function inside closure, Swift

private func showOrder() {
disableButtons()
var count = 0
_ = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { time in
self.popColor(color: self.colorOrder[count])
count += 1
if count == self.colorOrder.count {
time.invalidate()
self.depopAllButtons()
self.enableButtons()
}
}
}
In this function I am looping through an Array of colors. The popColor() method is used to add shadows and such to a button the screen.
The issue that I am having is that the popColor() function seems to execute after the closure has executed, so it is always one behind where it should be. The error this causes is on the last iteration of the loop the last color doesn't execute its popColor().
Is it possible to call a function inside of a closure as I am doing here with popColor()?
I have write your code with small changes:
var count = 0
_ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { time in
debugPrint("set color")
count += 1
if count == 3 {
time.invalidate()
debugPrint("disable set color")
}
}
And the console printed:
"set color"
"set color"
"set color"
"disable set color"
Your timer is working correctly. Look for a problem elsewhere.

Swift readLine! is causing fatal error "execution was interrupted"

I have this piece of code
func sell() throws{
while(true)
{
var choice : String?
print("Please press a number from 1 to 3\n")
let product = readLine(stripNewline: true)!
switch product
{
case "1":
//
case "2":
//
case "3":
//
default:
choice = "Invalid"
try sell()
}
}
try sell()
And it gives me the error
execution was interrupted reason exc_bad_instruction
I realized that the ! is causing the error. If I remove it I have a problem with the comparisons inside switch.
Anyone knows what is the problem?
func foo()->Int {
print("Please press a number from 1 to 3")
while true {
if let l = readLine(),
let i = Int(l) {
if (1..<4).contains(i) {
return i
} else {
print("Number must be in range from 1 to 3")
}
} else {
print("Please press a number")
}
}
}
let r = foo()
print("You chose", r)
an example of ...
Please press a number from 1 to 3
u
Please press a number
7
Number must be in range from 1 to 3
45
Number must be in range from 1 to 3
h76
Please press a number
1
You chose 1
Program ended with exit code: 0
How about create one if let to check if this contains value or is it nil
let product = readLine(stripNewline: true)
if let productNo = product {
switch productNo {
//your same code in switch
}

How to make a button reset to default state?

I have a button that has 2 switch statements.
buttonPressed() {
switch 1
switch 2
}
Switch 1 checks for errors. If no errors are found, Switch 2 executes. This part works great.
The problem is, when an error is found, on the second press of the button, switch 1 is skipped.
How do I make the button always execute from the start every time it is pressed?
It's as if it creates a breakpoint at the end of the switch, and the second press continues from that breakpoint.
Here's an excerpt of the switch1:
case 1:
let oneLength = countElements(textOne.text)
if oneLength <= 1 {
self.shouldSave = false
showAlertWithText(message: "First checklist item must have a value")
} else if oneLength >= 141 {
self.shouldSave = false
showAlertWithText(message: "First checklist item exceeds the 140 character limit")
} else {
newChecklistOne["goalID"] = self.dependantGoalID
newChecklistOne["itemDescription"] = textOne.text
newChecklistOne["isComplete"] = false
}
switch 2 example:
if self.shouldSave == true {
while self.saveVarTwo <= self.z {
switch self.saveVarTwo {
case 1: newChecklistOne.saveInBackground()
Here's the showAlertWithText function:
func showAlertWithText (header : String = "Ermahgerd!!!", message : String) {
var alert = UIAlertController(title: header, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
So, how do I make the button start executing code from line 1 on every button click?
So, I had a "saveVar" that worked as the switch catalyst for switch 1. It would iterate to the # of entries, but I never reset it when an error occurred. Therefore, when the button was pressed, the switch started at the max case.

Swift switches and case function handling

I'm working on an open source project while learning swift at the same time, the github repository is available at https://github.com/istx25/schedules. I'm trying to add an identifier to the case that will run a function everytime the button is pressed in a UIActionSheet. The code for the action sheet is as follows:
#IBAction func rightButton(sender : AnyObject) {
var sheet: UIActionSheet = UIActionSheet()
let title: String = "Please choose a block rotation"
sheet.title = title
sheet.delegate = self
sheet.addButtonWithTitle("Cancel")
sheet.addButtonWithTitle("Day Four")
sheet.addButtonWithTitle("Day Three")
sheet.addButtonWithTitle("Day Two")
sheet.addButtonWithTitle("Day One")
sheet.cancelButtonIndex = 0
sheet.showInView(self.view)
}
and I've started the switch to defer which button is which as:
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
case 0:
print("Go Back")
case 1:
print("Day Four")
// Day Four Function
case 2:
print("Day Three")
// Day Three Function
case 3:
print("Day Two")
// Day Two Function
case 4:
print("Day One")
// Day One Function
default:
print("Something's broken")
}
}
I'm wanting each case to be pushed to it's own func method and I'm not sure exactly how I would approach this, so please if anybody could help that would be great. If this question is hard to understand please tell me; so I can get better at asking for help on Stackoverflow! Thanks in advance.
If you're targeting iOS 8 then you shouldn't be using UIActionSheets as they are deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleActionSheet and add actions to it with the addAction() method.
I'm not familiar with Swift (yet), but the usual setup is not with switch/case. Instead each button is associated with an action. That might be a callback. Here, UIControl.sendAction and related code looks like the place to start.
You could create a separate func, and pass in buttonIndex. There you could either do if's or the same switch.
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex {
case 0:
print("Go Back")
theFuction(buttonIndex)
case 1:
print("Day Four")
// Day Four Function
theFuction(buttonIndex)
case 2:
print("Day Three")
// Day Three Function
theFuction(buttonIndex)
case 3:
print("Day Two")
// Day Two Function
theFuction(buttonIndex)
case 4:
print("Day One")
// Day One Function
theFuction(buttonIndex)
default:
print("Something's broken")
}
}
func theFuction (btnIndex: Int) {
if btnIndex == 0 {
} else if btnIndex == 1 {
} else if btnIndex == 2 {
} else if btnIndex == 3 {
} else if btnIndex == 4 {
}
}