首先你的ViewController需要实现 UITextFieldDelegate 代理,
其次,需要字数限制的UITextField实例的代理要设置成 self(ViewController)
然后实现下列代理方法:
Objective—C
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 5;//最大字数长度
}
swift:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let currentCharacterCount = textField.text?.characters.count ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length return newLength <= 25 }