- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
方法中参数理解
textView:文本框
range:输入文字所要替换位置和长度
text:替换文字内容
 
限制文本输入字数为10,判断逻辑是:中文状态下,每个汉字和符号都算一个字,在英文状态下,字母和符号都算半个字。针对这个来检查看看是否不符合条件,给出警告。符合条件的时候就发送。

 
  
  1. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
  2.     float sum = 0.0; 
  3.     for(int i=0;i<[textView.text length];i++) {  
  4.         NSString *character = [textView.text substringWithRange:NSMakeRange(i, 1)];  
  5.         if([character lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3) { 
  6.             sum++;  
  7.         }  
  8.         else { 
  9.             sum += 0.5;  
  10.         } 
  11.     }  
  12.     int bys = (int)(ceil(sum)); 
  13.     if (bys > =10) { 
  14.        UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:@""  message:@"输入的文字超过10位" delegate:self cancelButtonTitle:@"" otherButtonTitles:nil]; 
  15.        [alert show]; 
  16.        [alert release]; 
  17.        NSTimer showTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(hideAlertView:) userInfo:alertView repeats:NO]; 
  18.     } 
  19.     return (bys >= 10) ? NO:YES; 
  20.  
  21. - (void)hideAlertView:(NSTimer)timer { 
  22.    UIAlertView *alertView = timer.userInfo; 
  23.    [alertView dismissWithClickedButtonIndex:0 animated:YES];