Emoji是我們常見的在文字中插入的圖形符號,在iOS中可以實(shí)現(xiàn)程序自動(dòng)實(shí)現(xiàn)的方式實(shí)現(xiàn)此功能;即可在需要展示的文字中添加Emoji表情或者在應(yīng)用通知中添加。
按照現(xiàn)在理解,其實(shí)Emoij也就是一種編碼而已。使用一般會(huì)按照蘋果的使用規(guī)則和編碼方式進(jìn)行相應(yīng)的Emoij對應(yīng)。
實(shí)現(xiàn)代碼(.h/.m)如下:
NSString+Emoji.m實(shí)現(xiàn)代碼:
#import "NSString+Emoji.h"
@implementation NSString (Emoji)
static NSDictionary * s_unicodeToCheatCodes = nil;
static NSDictionary * s_cheatCodesToUnicode = nil;
+ (void)initializeEmojiCheatCodes
{
// 下面的NSDictionary展示的部分Emoji代碼
// 詳細(xì)Emoji代碼可見,已封裝完成的自定義表情NSString擴(kuò)展類中
NSDictionary *forwardMap = @{
@"??": @":smile:",
@"??": @[@":laughing:", @":D"],
@"??": @":blush:",
@"??": @[@":smiley:", @":)", @":-)"],
@"?": @":relaxed:",
@"??": @":smirk:",
@"??": @[@":disappointed:", @":("],
@"??": @":heart_eyes:"
};
NSMutableDictionary *reversedMap = [NSMutableDictionary dictionaryWithCapacity:[forwardMap count]];
[forwardMap enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
for (NSString *object in obj) {
[reversedMap setObject:key forKey:object];
}
} else {
[reversedMap setObject:key forKey:obj];
}
}];
@synchronized(self) {
s_unicodeToCheatCodes = forwardMap;
s_cheatCodesToUnicode = [reversedMap copy];
}
}
/* 方法使用示例:對照Emoji表情代碼
* Example:
* "This is a smiley face :smiley:"
* Will be replaced with:
* "This is a smiley face \U0001F604"
*/
- (NSString *)stringByReplacingEmojiCheatCodesWithUnicode
{
if (!s_cheatCodesToUnicode) {
[NSString initializeEmojiCheatCodes];
}
if ([self rangeOfString:@":"].location != NSNotFound) {
__block NSMutableString *newText = [NSMutableString stringWithString:self];
[s_cheatCodesToUnicode enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
[newText replaceOccurrencesOfString:key withString:obj options:NSLiteralSearch range:NSMakeRange(0, newText.length)];
}];
return newText;
}
return self;
}
/* Example:
"This is a smiley face \U0001F604"
Will be replaced with:
"This is a smiley face :smiley:"
*/
- (NSString *)stringByReplacingEmojiUnicodeWithCheatCodes
{
if (!s_cheatCodesToUnicode) {
[NSString initializeEmojiCheatCodes];
}
if (self.length) {
__block NSMutableString *newText = [NSMutableString stringWithString:self];
[s_unicodeToCheatCodes enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *string = ([obj isKindOfClass:[NSArray class]] ? [obj firstObject] : obj);
[newText replaceOccurrencesOfString:key withString:string options:NSLiteralSearch range:NSMakeRange(0, newText.length)];
}];
return newText;
}
return self;
}
@end
NSString+Emoji.h實(shí)現(xiàn)調(diào)用代碼:
Example:
// 加入Emoji表情
NSString *smileEmojiStr = @":blush:"; // 寫出此代碼對照表情
NSString *str = @"后接表情";
NSString *emojiStr = [str stringByReplacingEmojiCheatCodesWithUnicode];