美文网首页
文本框的字数控制(只显示中文)

文本框的字数控制(只显示中文)

作者: 再也不要见 | 来源:发表于2017-03-11 15:59 被阅读0次

    需求:  UITextFiled 限制只能输入4个中文;一起一切字符,禁止输入;

    解决方案:添加监听,在监听中,过滤字符;

    1,声明变量:

    @property (nonatomic, strong) UITextField *textField;

    2,添加监听:

    [[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,移除监听:

    - (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

    }

    5,Over;

    相关文章

      网友评论

          本文标题:文本框的字数控制(只显示中文)

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