实现效果:
通过textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool 代理方法对textField输入内容进行限制,保证只能输入有效金额。
实现思路:
首先设置TextField的keyboardType为.decimalPad,只能输入数字与小数点。之后在代理方法中,对输入字符为"."和"0"两种情况进行限制。
完整代码
let textField: UITextField = {
let textField = UITextField(frame: CGRect(x: 100, y: 200, width: 200, height: 50))
textField.keyboardType = .decimalPad
return textField
}()
extension ViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string == "." || string == "0" else { return true }
guard let text = textField.text else { return true }
if text.count == 0 {
textField.text = "0."
return false
}
if text.range(of: ".") != nil && string == "." {
return false
}
return true
}
}
demo地址: EWNumberTextField
有问题欢迎探讨.