I have an app that is crashing when a user inputs the wrong format in a text frame. How can I 1)make sure the keyboard is the right type (which would be a number keyboard in my case) and 2) make it so the app doesn't crash if a wrong format is input? Here is my code for this button:
@IBAction func resetDistanceWalkedGoalButton(sender: AnyObject) {
var distanceWalkedAlert = UIAlertController(title: "Distance Walked", message: "Current Goal: \(distanceWalkedGoal) miles – Enter a new goal. (e.g. '1.75')", preferredStyle: UIAlertControllerStyle.Alert)
distanceWalkedAlert.addTextFieldWithConfigurationHandler {
(textField) in
}
distanceWalkedAlert.addAction(UIAlertAction(title: "Submit", style: .Default, handler: {
(action) in
let textW = distanceWalkedAlert.textFields![0] as UITextField
print(textW)
textW.keyboardType = UIKeyboardType.NumberPad
let distanceWalkedGoalFromAlert = Double(textW.text!)
distanceWalkedGoal = distanceWalkedGoalFromAlert!
print(distanceWalkedGoal)
self.distanceWalkedGoalNumber.text = "\(distanceWalkedGoal)"
}))
distanceWalkedAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: {
(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(distanceWalkedAlert, animated: true, completion: nil)
}
you should setup properties for UItextfield in method addTextFieldWithConfigurationHandler and it will not crash