- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
方法中参数理解
textView:文本框
range:输入文字所要替换位置和长度
text:替换文字内容
限制文本输入字数为10,判断逻辑是:中文状态下,每个汉字和符号都算一个字,在英文状态下,字母和符号都算半个字。针对这个来检查看看是否不符合条件,给出警告。符合条件的时候就发送。
- - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
- float sum = 0.0;
- for(int i=0;i<[textView.text length];i++) {
- NSString *character = [textView.text substringWithRange:NSMakeRange(i, 1)];
- if([character lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3) {
- sum++;
- }
- else {
- sum += 0.5;
- }
- }
- int bys = (int)(ceil(sum));
- if (bys > =10) {
- UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:@"" message:@"输入的文字超过10位" delegate:self cancelButtonTitle:@"" otherButtonTitles:nil];
- [alert show];
- [alert release];
- NSTimer showTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(hideAlertView:) userInfo:alertView repeats:NO];
- }
- return (bys >= 10) ? NO:YES;
- }
- - (void)hideAlertView:(NSTimer)timer {
- UIAlertView *alertView = timer.userInfo;
- [alertView dismissWithClickedButtonIndex:0 animated:YES];
- }