UITextField限制字数的方法 .

来源:互联网 发布:c语言杨辉三角 编辑:程序博客网 时间:2024/04/30 02:27
 

在输入东西的时候,如果想限制最大字数,可以用下面方法

view plaincopy to clipboardprint?
  1. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;  
  2. {  
  3.     if ([string isEqualToString:@"\n"])   
  4.     {  
  5.         return YES;  
  6.     }  
  7.     NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];  
  8.       
  9.     if (self.myTextField == textField)   
  10.     {  
  11.         if ([toBeString length] > 20) {  
  12.             textField.text = [toBeString substringToIndex:20];  
  13.             UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];  
  14.             [alert show];  
  15.             return NO;  
  16.         }  
  17.     }  
  18.     return YES;  
  19. }  


原创粉丝点击