How can I override this UITextField function so that it will have a limit on the maximum number of characters?
override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
}
I've done some research on stack, but all I can find is this function (see below). First off, I can't see how this can be an override, and second, it's using NSRange as a parameter where I have UITextRange. How can this be implemented? thanks
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let currentString: NSString = textField.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= 4
}
My failed try:
override func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
let currentString: NSString = self.text! as NSString
let newString: NSString = currentString.replacingCharacters(in: range, with: text) as NSString
return newString.length <= 4
}
error: Cannot convert value of type 'UITextRange' to expected argument type 'NSRange' (aka '_NSRange')
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…