问题描述:在项目开发中,经常会碰到一个文本输入框对输入文本的长度的限制,每次的处理方式都不太统一,现在做一次总结。
对于输入内容长度的判断,应该放在UITextFieldDelegate的代理方法中来判断
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.titleField) {
if (string.length == 0) return YES;
NSInteger existedLength = textField.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = string.length;
if (existedLength - selectedLength + replaceLength > 20) {
return NO;
}
}
return YES;
}
此外,再给UITextField添加一个事件监听:
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField
{
if (textField == self.titleField) {
if (textField.text.length > 20) {
textField.text = [textField.text substringToIndex:20];
}
}
}
网友评论