2016-08-01 65 views
1

我有一个应用程序在用户在文本框架中输入错误的格式时发生崩溃。我怎样才能1)确保键盘是正确的类型(在我的情况下,这将是一个数字键盘),2)使它成为应用程序不会崩溃,如果输入了错误的格式?这是我对这个按钮的代码:如何确保输入在Swift中正确格式化

@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) 



} 

回答

0

你应该在方法addTextFieldWithConfigurationHandler为UITextField设置属性,它不会崩溃

alertController.addTextFieldWithConfigurationHandler { (textField) in 
     textField.placeholder = "Enter RSS Link here ..." 
     textField.text = link 
     textField.keyboardType = UIKeyboardType.NumberPad 

     // add Notification to handle text input if you need 
     NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.textDidChange), name: UITextFieldTextDidChangeNotification, object: linkTextField) 

    } 
1

确保键盘是正确的类型(这将是在我的情况下,数字键盘)

其实,你不需要改变你当前的任何代码!

textW.keyboardType = .NumberPad 

但请注意,iPad没有数字键盘键盘。如果您想在iPad上显示数字键盘,则必须创建自己的键盘。

使它所以如果一个错误的格式输入

这需要更多一点的工作应用程序不会崩溃。在为“提交”动作的动作处理程序,做一些检查你的字符串转换后翻番:

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!) 

    guard distanceWalkedGoalFromAlert != nil else { 
     // if code execution goes here, this means that invalid input is detected. 
     // you can show another alert telling the user that here. 
     return 
    } 

    distanceWalkedGoal = distanceWalkedGoalFromAlert! 

    print(distanceWalkedGoal) 
    self.distanceWalkedGoalNumber.text = "\(distanceWalkedGoal)" 

})) 

或者你也可以干脆尝试WKTextFieldFormatter阻断无效的输入。