如果字符数超过 200,我将尝试删除 UITextField 中的最后一个字符。但它没有任何效果:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print(textField.text?.characters.count)
if (textField.text?.characters.count > 200){
self.textField.shake()
self.textField.becomeFirstResponder()
self.textField.text?.characters.dropLast()
}
return true
}
最佳答案
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
{
let textFieldString = textField.text! as NSString;
var newString = textFieldString.stringByReplacingCharactersInRange(range, withString:string)
if newString.characters.count > 200 {
// This will remove just last character, If u want to remove all the characters starting from 201st character pass 200 to substringToIndex method
newString = newString.substringToIndex(newString.endIndex.advancedBy(-1))
textField.text = newString
return false
}
return true
}
关于ios - 删除 UITextField 中的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35863061/