iOS UITextfield input int

需求 :iOS UITextfield 只允许输入数字 粘贴板如果有除数字之外的字符全部过滤掉,只允许数字上屏显示

  1. 设置键盘样式 keyboardtype = UIKeyboardTypeASCIICapableNumberPad;
    • (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
      if ([self validateIncludeInt:string]) {
      NSScanner *scanner = [NSScanner scannerWithString:string];
      [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
      int number;
      [scanner scanInt:&number];
      NSString *stringNumber = [NSString stringWithFormat:@"%d",number];
      [textField replaceRange:textField.selectedTextRange withText:stringNumber];
      }
      return [string isEqualToString:@""];
      }
  • (BOOL)validateIncludeInt:(NSString *)stringInput {
    NSScanner *scanner = [NSScanner scannerWithString:stringInput];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    int number;
    return [scanner scanInt:&number];
    }
  • (BOOL)validateOnlyChinese:(NSString *)stringInput {
    BOOL result = NO;
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@",match];
    result = [predicate evaluateWithObject:stringInput];
    return result;
    }
  • (BOOL)validateIncludeChinese:(NSString *)stringInput {
    BOOL result = NO;
    for(int i=0; i< [stringInput length];i++) {
    int a = [stringInput characterAtIndex:i];
    if( a > 0x4e00 && a < 0x9fff){
    result = YES;
    }
    }
    return result;
    }

你可能感兴趣的:(iOS UITextfield input int)