Ich habe eine App, die abstürzt, wenn ein Benutzer das falsche Format in einen Textrahmen eingibt. Wie kann ich 1) sicherstellen, dass die Tastatur der richtige Typ ist (was in meinem Fall eine Zifferntastatur wäre) und 2) es so machen, dass die App nicht abstürzt, wenn ein falsches Format eingegeben wird? Hier ist mein Code für diese Schaltfläche:So stellen Sie sicher, dass die Eingabe in Swift korrekt ist
@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)
}