【问题标题】:Add attributes to all emoji in an NSAttributedString?为 NSAttributedString 中的所有表情符号添加属性?
【发布时间】:2015-06-23 12:56:23
【问题描述】:

我在我的 iOS 应用程序中使用的字体有一个不幸的品质:它的字符非常小,因此,如果用户输入包含表情符号的字符串(或者可能是字体中未包含的其他字符?还没有测试过),当 iOS 以 AppleColorEmoji 字体绘制这些字形时,它们相对于其他字形显得很大。

由于 emoji 是“两部分”字形,这当然很复杂,所以我不能只做一个简单的 for-each-character-in-the-string 循环。

我需要的是一种类似的方法 -(NSAttributedString *)attributedStringByAddingAttributes:(NSArray *)attrs toString:(NSString*)myString forCharactersNotInFont:(UIFont *)font

... 或者至少失败了 -(NSAttributedString *)attributedStringByAddingAttributes:(NSArray *)attrs toStringForEmoji:(NSString*)myString

...什么的。

不确定最好的方法。

【问题讨论】:

    标签: ios uilabel nsattributedstring emoji


    【解决方案1】:

    我最终得到的代码,使用改编自 here 的代码:

    - (BOOL)isEmoji:(NSString *)str {
        const unichar high = [str characterAtIndex: 0];
    
        // Surrogate pair (U+1D000-1F77F)
        if (0xd800 <= high && high <= 0xdbff) {
            const unichar low = [str characterAtIndex: 1];
            const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
    
            return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
    
            // Not surrogate pair (U+2100-27BF)
        } else {
            return (0x2100 <= high && high <= 0x27bf);
        }
    }
    
    // The following takes a string s and returns an attributed string where all the "special characters" contain the provided attributes
    
    - (NSAttributedString *)attributedStringForString:(NSString *)s withAttributesForEmoji:(NSDictionary *)attrs {
    
        NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:@""];
    
        NSRange fullRange = NSMakeRange(0, [s length]);
    
        [s enumerateSubstringsInRange:fullRange
                              options:NSStringEnumerationByComposedCharacterSequences
                           usingBlock:^(NSString *substring, NSRange substringRange,
                                        NSRange enclosingRange, BOOL *stop)
        {
            if ([self isEmoji:substring]) {
                [as appendAttributedString:[[NSAttributedString alloc] initWithString:substring
                                                                           attributes:attrs]];
            } else {
                [as appendAttributedString:[[NSAttributedString alloc] initWithString:substring]];
            }
        }];
        return as;
    }
    

    到目前为止,似乎工作得很好!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2020-07-15
      • 2016-02-29
      • 2011-04-30
      • 1970-01-01
      • 2014-02-22
      相关资源
      最近更新 更多