ios - shouldChangeCharactersInRange 接受单个 '.'

标签 ios swift uitextfield decimal

我有一个仅接受数值的文本字段。我想知道如何才能包含输入单个“.”的功能。来表示小数点。

我有以下代码:

class ViewController: UIViewController, UITextFieldDelegate {

    var formatter: NSNumberFormatter!

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    return string == "" || Double(string) != nil
    }

    override func viewDidLoad() {
        amountTextField.delegate = self
        // Initialize the formatter; minimum value is set to zero; style is Decimal.
        formatter = NSNumberFormatter()
        formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
        formatter.minimum = 0
    }
}

最佳答案

您必须使用此文本字段委托(delegate)方法:

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // return NO to not change text

        let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if newString.characters.count > 0 {

            let scanner: NSScanner = NSScanner(string:newString)
            let isNumeric = scanner.scanDecimal(nil) && scanner.atEnd

            return isNumeric

        } else {

            return true
        }
    }

关于ios - shouldChangeCharactersInRange 接受单个 '.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772857/

相关文章:

ios - 证书固定在 swift 3/Alamofire 4 中停止工作?

ios - NSClassFromString 在 OC 中运行良好,但在 Swift 中崩溃

ios - 在不阻止清除按钮的情况下禁用文本字段编辑

ios - 在文本字段中键入时在文本字段字符之间添加空格

ios - 由于 MBProgressHud,XCUI 测试失败

ios - NSUserDefaults 是否包含值?

ios - 新 PayPal iOS SDK 中的实时凭证

random - 如何在 Swift 中播种随机数生成器?

ios - 如何让 UITextField 的 textContentType 属性执行任何操作?

ios - 移位的核心图 x 轴标签