iOS UITextField 限制只能输入中文

需求:限制UITextField只能输入中文,并且最大长度为4;
解决方案:直接上干货!
1,先声明一个UITextfield 变量;
@property (nonatomic, strong) UITextField *textField;
2,添加通知;

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)name:UITextFieldTextDidChangeNotification object:self.textField];
    }
    3,在监听中,实现过滤非中文字符,并限制字符数量;

  • (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];

    //过滤非汉字字符
    textField.text = [self filterCharactor:textField.text withRegex:@"[^\u4e00-\u9fa5]"];

    if (textField.text.length >= 4) {
    textField.text = [textField.text substringToIndex:4];

    }
    return NO;
    }

  • (void)textFiledEditChanged:(id)notification{

    UITextRange *selectedRange = self.textField.markedTextRange;
    UITextPosition *position = [self.textField positionFromPosition:selectedRange.start offset:0];

    if (!position) { //// 没有高亮选择的字
    //过滤非汉字字符
    self.textField.text = [self filterCharactor:self.textField.text withRegex:@"[^\u4e00-\u9fa5]"];

      if (self.textField.text.length >= 4) {
          self.textField.text = [self.textField.text substringToIndex:4];
      }
    

    }else { //有高亮文字
    //do nothing
    }
    }

//根据正则,过滤特殊字符

  • (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
    }
    4,Game over.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容