如何分离在文本字段上输入的表情符号(通过默认键盘)

How to separate emojis entered (through default keyboard) on textfield

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

我正在寻找 swift 代码,我可以在其中分别分隔每个表情符号,假设按照上面的例子我应该得到 2 strings/character 分别为每个表情符号。

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

提前致谢。

更新 Swift 4 (Xcode 9)

截至 Swift 4(使用 Xcode 9 beta 测试)"Emoji ZWJ Sequence" 是 按照 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(零宽度连接器)粘合在一起:

for c in str.unicodeScalars {
    print(String(c.value, radix: 16))
}

/* Output:
1f468
200d
1f468
200d
1f467
200d
1f467
1f60d
*/

.ByComposedCharacterSequences枚举字符串 选项正确组合了这些字符:

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

// Output: ["‍‍‍", ""]

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

let str = ""

以上循环的结果是

["", ""]

这不是想要的结果。

完整规则在"3 Grapheme Cluster Boundaries"中定义 在 "Standard Annex #29 UNICODE TEXT SEGMENTATION" 中 统一码标准。

您可以使用此代码 example or this 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