如何确保在Swift中正确格式化输入

时间:2016-08-01 05:01:11

标签: swift uikeyboard uikeyboardtype

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

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



}

2 个答案:

答案 0 :(得分:1)

  

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

实际上,您无需更改任何当前代码!

textW.keyboardType = .NumberPad

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

  

如果输入错误的格式,应用程序不会崩溃

这需要更多的工作。在“提交”操作的操作处理程序中,在将字符串转换为double后执行一些检查:

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来阻止无效输入。

答案 1 :(得分: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)

    }