【发布时间】:2016-10-19 08:37:17
【问题描述】:
我正在尝试检测我的应用程序的用户是否在 UITextView 中输入了表情符号。我找到了这段代码:
https://gist.github.com/cihancimen/4146056
但是,此代码不适用于所有表情符号(例如,它不适用于壁炉符号)。有谁知道如何改进代码以捕获所有表情符号?我正在使用 Objective-C 语言。任何帮助表示赞赏。
【问题讨论】:
我正在尝试检测我的应用程序的用户是否在 UITextView 中输入了表情符号。我找到了这段代码:
https://gist.github.com/cihancimen/4146056
但是,此代码不适用于所有表情符号(例如,它不适用于壁炉符号)。有谁知道如何改进代码以捕获所有表情符号?我正在使用 Objective-C 语言。任何帮助表示赞赏。
【问题讨论】:
这就是我在我的应用程序中的做法:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if textView.textInputMode?.primaryLanguage == "emoji" || textView.textInputMode?.primaryLanguage == nil {
// An emoji was typed by the user
// Do anything you need to do (or return false to disallow emojis)
}
return true
}
【讨论】:
如果您需要能够检测任何表情符号,则需要创建一个列表,其中包含用于表情符号的所有代码点(或者,如果您愿意,也可以创建一个所有表情符号的列表)。如果您愿意,可以查看this framework 中如何检测表情符号,我创建该表情符号的目的是用自定义图像替换标准表情符号,或查看my answer to a related question。
然后,如果您使用的是 Objective-C 和 NSString 类型,您首先必须将字符串的 unichars(采用 UTF-16 编码)依次转换为 UTF-32 兼容格式使用您的代码点列表。当您拥有 UTF-32 值时,只需将其与您的列表进行比较并根据需要进行处理:
// Sample text.
NSString *text = @"a ?";
// Get the UTF-16 representation of the text.
unsigned long length = text.length;
unichar buffer[length];
[text getCharacters:buffer];
// Initialize array to hold our UTF-32 values.
NSMutableArray *array = [[NSMutableArray alloc] init];
// Temporary stores for the UTF-32 and UTF-16 values.
UTF32Char utf32 = 0;
UTF16Char h16 = 0, l16 = 0;
for (int i = 0; i < length; i++) {
unichar surrogate = buffer[i];
// High surrogate.
if (0xd800 <= surrogate && surrogate <= 0xd83f) {
h16 = surrogate;
continue;
}
// Low surrogate.
else if (0xdc00 <= surrogate && surrogate <= 0xdfff) {
l16 = surrogate;
// Convert surrogate pair to UTF-32 encoding.
utf32 = ((h16 - 0xd800) << 10) + (l16 - 0xdc00) + 0x10000;
}
// Normal UTF-16.
else {
utf32 = surrogate;
}
// Compare the UTF-32 value against your list of code points, and handle.
// Just demonstrating with the code point for ?.
if (utf32 == 0x1f601) {
NSLog(@"It's an emoji!");
}
}
此外,如果您不想要误报,则需要处理 Variation Selectors,如果您需要能够处理序列,则需要处理 zero-width joiners,但只需查看序列中的第一个字符就会告诉您字符串是否包含表情符号,所以我不再赘述。
【讨论】: