【问题标题】:How to separate emojis entered (through default keyboard) on textfield如何在文本字段上分隔输入的表情符号(通过默认键盘)
【发布时间】:2016-04-04 02:54:10
【问题描述】:

我在文本字段中输入了两个表情符号 ??????‍????‍??????‍????????,这里我得到了 5 个字符长度的总数,而第一个字符是 4 个字符表情符号和第二个字符。看起来苹果已经将 4 个表情符号组合成一个。

我正在寻找 swift 代码,我可以在其中分别分隔每个表情符号,假设通过上面的示例,我应该为每个表情符号分别获取 2 个字符串/字符。

谁能帮我解决这个问题,我尝试了很多东西,比如正则表达式分离或 componentsSeparatedByString 或 characterSet。但不幸的是,结果是否定的。

提前致谢。

【问题讨论】:

    标签: ios swift emoji


    【解决方案1】:

    Swift 4 (Xcode 9) 更新

    从 Swift 4(使用 Xcode 9 beta 测试)开始,“Emoji ZWJ 序列”是 按照 Unicode 9 标准的要求,将其视为单个 Character

    let str = "?‍?‍?‍??"
    print(str.count) // 2
    print(Array(str)) //  ["?‍?‍?‍?", "?"]
    

    另外String 是它的字符的集合(再次),所以我们可以 调用str.count 获取长度,调用Array(str) 获取所有 字符作为数组。


    (Swift 3 及更早版本的旧答案)

    这只是部分答案,可能对这种特殊情况有所帮助。

    “?‍?‍?‍?”确实是四个独立字符的组合:

    let str = "?‍?‍?‍??" //
    print(Array(str.characters))
    
    // Output: ["?‍", "?‍", "?‍", "?", "?"]
    

    用 U+200D (ZERO WIDTH JOINER) 粘合在一起:

    for c in str.unicodeScalars {
        print(String(c.value, radix: 16))
    }
    
    /* Output:
    1f468
    200d
    1f468
    200d
    1f467
    200d
    1f467
    1f60d
    */
    

    使用.ByComposedCharacterSequences 枚举字符串 options 正确组合了这些字符:

    var chars : [String] = []
    str.enumerateSubstringsInRange(str.characters.indices, options: .ByComposedCharacterSequences) {
        (substring, _, _, _) -> () in
        chars.append(substring!)
    }
    print(chars)
    
    // Output: ["?‍?‍?‍?", "?"]
    

    但在其他情况下这不起作用, 例如作为“区域指标”序列的“标志” 个字符”(比较 Swift countElements() return incorrect value when count flag emoji)。与

    let str = "??"
    

    上述循环的结果是

    ["?", "?"]
    

    这不是我们想要的结果。

    完整的规则定义在"3 Grapheme Cluster Boundaries" 在“标准附件#29 UNICODE TEXT SEGMENTATION”中 Unicode 标准。

    【讨论】:

    • 嗨,马丁。首先非常感谢您的回答。正如您所说,在某些情况下这不起作用,但我尝试了您的代码并且它工作正常。这是我的完整字符串,带有许多标志 ["??????????"],它已被分隔为 ["??"、"??"、"??"、"??"、"? ?”]。从昨天开始,我试图解决的另一件事是,但无法解决。你能告诉我你是如何学习这些东西的以及我应该更喜欢哪些文档吗?
    • 我也用标志尝试了这个逻辑,它适用于几个不同的标志。
    • @KiranJasvanee:“问题”已在 Swift 4(目前为测试版)中得到修复。
    【解决方案2】:

    您可以使用此代码example 或此pod

    要在 Swift 中使用它,请将类别导入 YourProject_Bridging_Header

    #import "NSString+EMOEmoji.h"
    

    然后您可以检查字符串中每个表情符号的范围:

    let example: NSString = "?‍?‍?‍??" // your string
    
    let ranges: NSArray = example.emo_emojiRanges()  // ranges of the emojis
    
    for value in ranges {
    
       let range:NSRange = (value as! NSValue).rangeValue
    
        print(example.substringWithRange(range))
    }
    
    
    // Output: ["?‍?‍?‍?", "?"]
    

    I created an small example project with the code above.

    为了进一步阅读,这篇来自Instagram的有趣文章。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-18
      • 2017-09-11
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多