如何知道两个表情符号是否会显示为一个表情符号?

时间:2016-08-23 14:37:03

标签: ios swift string unicode emoji

表情符号由2个unicodeScalars U + 1F44D,U + 1F3FC组成。

如何将其识别为1'显示'表情符号,因为它将在iOS上显示?

1 个答案:

答案 0 :(得分:18)

更新Swift 4(Xcode 9)

从Swift 4开始,“表情符号序列”被视为单个字素 集群(根据Unicode 9标准):

let s = "ab‍❤️‍‍"
print(s.count) // 4

因此不再需要其他解决方法了。

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

一个可能的选择是枚举和计算 字符串中的“组合字符序列”:

let s = "ab‍❤️‍‍"
var count = 0
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex,
                             options: .ByComposedCharacterSequences) {
                                (char, _, _, _) in
                                if let char = char {
                                    count += 1
                                }
}
print(count) // 4

另一种选择是找到组合字符的范围 给定指数的序列:

let s = "‍❤️‍‍"
if s.rangeOfComposedCharacterSequenceAtIndex(s.startIndex) == s.characters.indices {
    print("This is a single composed character")
}

作为String扩展方法:

// Swift 2.2:
extension String {
    var composedCharacterCount: Int {
        var count = 0
        enumerateSubstringsInRange(characters.indices, options: .ByComposedCharacterSequences) {
            (_, _, _, _) in count += 1
        }
        return count
    }

    var isSingleComposedCharacter: Bool {
        return rangeOfComposedCharacterSequenceAtIndex(startIndex) == characters.indices
    }
}

// Swift 3:
extension String {
    var composedCharacterCount: Int {
        var count = 0
        enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) {
            (_, _, _, _) in count += 1
        }
        return count
    }

    var isSingleComposedCharacter: Bool {
        return rangeOfComposedCharacterSequence(at: startIndex) == startIndex..<endIndex
    }
}

示例:

"".composedCharacterCount // 1
"".characters.count       // 2

"‍❤️‍‍".composedCharacterCount // 1
"‍❤️‍‍".characters.count       // 4

"".composedCharacterCount // 2
"".characters.count       // 1

如您所见,Swift字符(扩展字形集群)的数量可以或更少 组合字符序列的数量。