在输入东西的时候,如果想限制最大字数,可以用下面方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
if ([string isEqualToString:@"\n"])
{
return YES;
}
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (self.myTextField == textField)
{
if ([toBeString length] > 20) {
textField.text = [toBeString substringToIndex:20];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];
[alert show];
return NO;
}
}
return YES;
}
本文介绍了一个用于限制 UITextField 输入字数的方法。通过实现 textField:shouldChangeCharactersInRange:replacementString: 方法,当输入超过预设的最大长度时,会截断文本并提示用户。

3172

被折叠的 条评论
为什么被折叠?



