美文网首页
iOS UITextField 限制只能输入中文

iOS UITextField 限制只能输入中文

作者: iOS_永宝 | 来源:发表于2016-09-27 18:13 被阅读3330次

需求:限制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.

相关文章

网友评论

      本文标题:iOS UITextField 限制只能输入中文

      本文链接:https://www.haomeiwen.com/subject/ecthyttx.html