IOS textfield can only input a certain length of characters

From , 3 Years ago, written in Objective-C, viewed 93 times.
URL https://pastebin.vip/view/e3019767
  1. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
  2. {  //string就是此时输入的那个字符textField就是此时正在输入的那个输入框返回YES就是可以改变输入框的值NO相反
  3.      
  4. if ([string isEqualToString:@"\n"])  //按会车可以改变
  5.     {
  6.         return YES;
  7.     }
  8.   
  9.     NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
  10.   
  11.     if (self.myTextField == textField)  //判断是否时我们想要限定的那个输入框
  12.     {
  13.         if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告
  14.             textField.text = [toBeString substringToIndex:20];
  15.             UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];
  16.             [alert show];
  17.             return NO;
  18.         }
  19.     }
  20.     return YES;
  21. }
  22. //objectc/5845

Reply to "IOS textfield can only input a certain length of characters"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website