Skip to content

Instantly share code, notes, and snippets.

@iT-Boyer
Last active January 28, 2021 12:20
Show Gist options
  • Save iT-Boyer/d17ccddc630992c87d66f4b8f1d96f06 to your computer and use it in GitHub Desktop.
Save iT-Boyer/d17ccddc630992c87d66f4b8f1d96f06 to your computer and use it in GitHub Desktop.
#pragma mark  ----  UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    // 根据字符数量显示或者隐藏 `placeholderLabel`
    if (textView.text.length > 0 && [text isEqualToString:@"\n"] == YES) {
        [textView resignFirstResponder];
        return NO;
    }
    //九宫格输入码误判为表情,处理
    if ([text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""]) {
        
        return YES;
    }
    if ([[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"]
        || [self stringContainsEmoji:text]) {
        return NO;
    }

    NSString *new = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger res = 150-[new length];
    if(res > 0){
        self.numberLab.text = [NSString stringWithFormat:@"%lu/150",new.length];
        return YES;
    }else{
        NSRange rg = {0,[text length]+res};
        if (rg.length>0) {
            NSString *s = [text substringWithRange:rg];
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        self.numberLab.text = @"150/150";
        [MBProgressHUD displayHudError:@"您输入超过最大长度"];
        return NO;
    }
    return YES;
}

- (BOOL)stringContainsEmoji:(NSString *)text{
    if (!text.length) return false;
    //九宫格输入码误判为表情,处理
    if ([text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""] || [text isEqualToString:@""]) {
        return false;
    }
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@""];
    return text.length != modifiedString.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment