我有一个UITextView,希望限制用户输入的字符数。我也尝试过在文本框为空时显示警告,但没有成功。
textview.h
@property (nonatomic,strong) IBOutlet UITextView *textField;
@property (nonatomic, retain) NSString *userText;
textview.m
- (IBAction)next:(id)sender {
self.userText = self.textField.text;
if ([self.textField.text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
message:@"Enter some text"
delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}
以下是似乎无法正常工作的文本限制方法:
- (BOOL)textView:(UITextView *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(range.length + range.location > textField.text.length)
{
return NO;
} else {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 70;
return (textField.text.length <= 70);
}
}