UITextView用法总结

过滤Emoj表情

笔者在开发的过程中,项目中有一个类似于微信朋友圈的功能,在发布文字的时候,有时候可能输入苹果的Emoji表情符号,但是后台没有支持,所以在前端需要过滤掉Emoji表情,读者有时候可能和笔者一样的需求,一言不合上代码

iOS检测字符串中是否包含emoji表情(包含iOS9之后的)
扩展的链接

  • 1.判断字符串是否为Emoji
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    -(BOOL)stringContainsEmoji:(NSString *)string
    {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
    options:NSStringEnumerationByComposedCharacterSequences
    usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    const unichar high = [substring characterAtIndex: 0];
    // Surrogate pair (U+1D000-1F9FF)
    if (0xD800 <= high && high <= 0xDBFF) {
    const unichar low = [substring characterAtIndex: 1];
    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
    returnValue = YES;
    }
    // Not surrogate pair (U+2100-27BF)
    } else {
    if (0x2100 <= high && high <= 0x27BF){
    returnValue = YES;
    }
    }
    }];
    return returnValue;
    }
  • 2.在UITextView的代理方法-(BOOL)textView:(UITextView )textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString )text调用判断方法,该代理方法在每次输入文字的时候都会调用,能够对每个输入的字符做出判断
1
2
3
4
5
6
7
8
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if( [self stringContainsEmoji:text]) {
[self showHudShort:@"不支持表情哦!"];
return NO;
}
return YES;
}