I want to achieve following:
I am using decimal keypad. Below code handles first and third item above:
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
}
Thank you for your time.
Bellow code will check all conditions you have specified
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
}