Swift:Textfield应该只允许4位数字,如小数点后的2000.034785,它可以允许' n'数字

时间:2017-05-27 18:15:57

标签: ios swift uitextfield

对于快速语言来说,这是非常新的,任何帮助都很明显,这是我的代码

::fe::
    Transform, CtrlC, Chr, 3 ; comes from ahk input documentation, I never really understood how this is supposed to work but I guess there is a code for alt 9 as well somehow
    input, key, L1 I M ; wait for the next 1 key
    if(key==CtrlC)
        sendraw forExample
return

当我在texfield中输入数字时,它会将数字提升到无穷大。请帮助我如何限制文本字段只允许我的代码中的4位数。

1 个答案:

答案 0 :(得分:2)

第一点,shouldChangeCharactersInRange不是副作用的方法。它不应该改变任何状态,它不应该改变文本字段的值。它应该只返回真或假。

根据我的理解,你想禁止在小数点左边输入四位以上的数字。

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)
        let number = Float(newText)
        return newText.isEmpty || newText == "." || number != nil && number! < 10000
    }
}
相关问题