I have an game app where players count cows on road trip. I have a button that comes up with an alert that allow players to enter however many cows they see. I had an error where if they pressed "add" without entering any cows, it would come up nil and crash. So I set the alert text field to equal "0." However, now if they add, say, 25 cows, the text field would read 025 (it still enters it as only 25 and doesn't cause problems with the math). I would like to clear the text field when players start adding numbers, but I'm not sure how to do that with a text field within an alert. I successfully did it in other areas of the app, so I'm familiar with how it works. Just not this specific instance (if it is in fact even different).
Here's the creation of the alert (I cut out all the math inside as I don't think that's relevant, but let me know if you think it's needed.):
@IBAction func playerOneSawCows(_ sender: UIButton) {
var textField = UITextField()
let alert = UIAlertController(title: "Cows Spotted!", message: "How many cows did you see?", preferredStyle: .alert)
let actionCancel = UIAlertAction(title: "False Alarm", style: .cancel)
let action = UIAlertAction(title: "Add Cows", style: .default) {(action) in
//MARK: - first cows
var totalCows = self.totalCowsOne
var additionalCows = 0
let newCows = textField.text!
let cowsNumber = Int(newCows)
var cowArrayOne: [String] = []
if self.numberOfCowsPlayerOne.text == "0 cows"{
...
}
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = ""
alertTextField.text = "0"
textField = alertTextField
textField.keyboardType = UIKeyboardType.numberPad
}
alert.addAction(action)
alert.addAction(actionCancel)
present (alert, animated: true, completion: nil)
}
And here's my previous instance of clearing a text field that works correctly:
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField == playerOneNameText) {
playerOneNameText.text = ""
}
else if (textField == playerTwoNameText) {
playerTwoNameText.text = ""
}else {
print("No players")
}
}
I tried adding another if statement there, but it didn't seem to trigger it. I feel like it's an easy solution, but I could be wrong. Any help would be great.