我要实现以下目标:
价值观。 (无需多说“。”。)
不能是“003”,“01”,“000012”等值。)
我正在使用十进制键盘。下面的代码处理上面的第一和第三项:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString: NSString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return newString.count <= 10
}
感谢您的时间。
最佳答案
波纹管代码将检查您指定的所有条件
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
if textfield.text?.count == 0 && string == "0" {
return false
}
//Limit the character count to 10.
if ((textfield.text!) + string).count > 10 {
return false
}
//Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
if (textfield.text?.contains("."))! && string == "." {
return false
}
//Only allow numbers. No Copy-Paste text values.
let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
let textCharacterSet = CharacterSet.init(charactersIn: textfield.text! + string)
if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
return false
}
return true
}