聊天輸入框常需要「文字裡夾雜表情圖片」的效果,這在 iOS 上要靠 NSAttributedString + NSTextAttachment 來完成。以下整理三個實務上一定會用到的操作。
用一份 plist 對應表把表情文字與圖片檔名配起來:
+ (NSMutableAttributedString *)stringToAttributeString:(NSString *)text {
// 先把普通字串轉成屬性字串
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
// 以 [表情名稱] 這種形式作為通配符,例如 [呵呵]
NSString *zhengze = @"\\[[a-zA-Z0-9\u4e00-\u9fa5]+\\]";
NSError *error = nil;
NSRegularExpression *re =
[NSRegularExpression regularExpressionWithPattern:zhengze
options:NSRegularExpressionCaseInsensitive
error:&error];
if (!re) {
NSLog(@"%@", [error localizedDescription]);
return attStr;
}
// 找出字串中所有的表情通配符
NSArray *arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"emotions" ofType:@"plist"];
NSArray *face = [[NSArray alloc] initWithContentsOfFile:path];
// 多個表情時必須「從後往前」替換,因為替換後 range 會失真
for (int j = (int)arr.count - 1; j >= 0; j--) {
NSTextCheckingResult *result = arr[j];
for (int i = 0; i < face.count; i++) {
if ([[text substringWithRange:result.range] isEqualToString:face[i][@"chs"]]) {
NSString *imageName = face[i][@"png"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:imageName];
NSAttributedString *imageStr =
[NSAttributedString attributedStringWithAttachment:textAttachment];
[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];
break;
}
}
}
return attStr;
}
為什麼要從後往前替換? NSTextAttachment 佔的長度是 1,而 [呵呵] 這種文字佔 4 個字元。一旦前面的片段被替換掉,後面所有 match 的 range 就全部錯位了。從尾端處理可以避免這個問題。
+ (CGSize)getAttributedTextSize:(NSString *)text {
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
NSString *zhengze = @"\\[[a-zA-Z0-9\u4e00-\u9fa5]+\\]";
NSError *error = nil;
NSRegularExpression *re =
[NSRegularExpression regularExpressionWithPattern:zhengze
options:NSRegularExpressionCaseInsensitive
error:&error];
if (!re) {
NSLog(@"正則表達式匹配錯誤 %@", [error localizedDescription]);
}
NSArray *arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
// 沒有表情,就是純文字,直接算文字尺寸
if (!arr.count) {
NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
CGSize size1 = [text boundingRectWithSize:CGSizeMake(160, 1000)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:dic
context:nil].size;
if (size1.height <= 60) {
size1.height = 60;
} else {
size1.height += 15;
}
return size1;
}
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"emotions" ofType:@"plist"];
NSArray *face = [[NSArray alloc] initWithContentsOfFile:path];
// 同樣從後往前替換
for (int j = (int)arr.count - 1; j >= 0; j--) {
NSTextCheckingResult *result = arr[j];
for (int i = 0; i < face.count; i++) {
if ([[text substringWithRange:result.range] isEqualToString:face[i][@"chs"]]) {
NSString *imageName = face[i][@"png"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:imageName];
NSAttributedString *imageStr =
[NSAttributedString attributedStringWithAttachment:textAttachment];
[attStr replaceCharactersInRange:result.range withAttributedString:imageStr];
break;
}
}
}
CGSize size2 = [attStr boundingRectWithSize:CGSizeMake(180, 1000)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size;
size2.height += 40; // 含表情時額外增加高度
return size2;
}
要注意 NSTextAttachment 圖片的高度會直接影響行高。實務上通常會設定 textAttachment.bounds,例如 CGRectMake(0, -3, 20, 20),讓表情與文字基線對齊、大小一致,否則算出的尺寸會偏大。
關鍵點在於「圖片的二進位比對」——從 attachment 拿到 UIImage 後,反查它對應的表情文字。
// 取得所有表情圖的路徑
- (NSArray *)getAllImagePaths {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"emotions" ofType:@"plist"];
NSArray *face = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *paths = [NSMutableArray array];
for (NSDictionary *dict in face) {
NSString *imagePath = [[bundle resourcePath] stringByAppendingPathComponent:dict[@"png"]];
[paths addObject:imagePath];
}
return paths;
}
// 以圖片的 PNG 二進位內容反查表情名稱
- (NSString *)stringFromImage:(UIImage *)image {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"emotions" ofType:@"plist"];
NSArray *face = [[NSArray alloc] initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image);
if (!imageData) {
return @"";
}
for (NSDictionary *dict in face) {
NSString *imagePath = [[bundle resourcePath] stringByAppendingPathComponent:dict[@"png"]];
NSData *target = [NSData dataWithContentsOfFile:imagePath];
if ([target isEqualToData:imageData]) {
return dict[@"chs"];
}
}
return @"";
}
以下以 UITextView 為例,UILabel、UIButton 同理:
// 把帶圖片的屬性字串轉成普通字串
- (NSString *)textString {
NSAttributedString *att = self.attributedText;
NSMutableAttributedString *resultAtt =
[[NSMutableAttributedString alloc] initWithAttributedString:att];
__weak __typeof(self) weakSelf = self;
// 列舉所有屬性,取出其中的附件
[att enumerateAttributesInRange:NSMakeRange(0, att.length)
options:NSAttributedStringEnumerationReverse
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
NSTextAttachment *textAtt = attrs[NSAttachment];
if (textAtt) {
UIImage *image = textAtt.image;
NSString *text = [weakSelf stringFromImage:image];
[resultAtt replaceCharactersInRange:range withString:text];
}
}];
return resultAtt.string;
}
二進位比對每換算一張圖就要讀一次檔案,表情多、字串長時會明顯卡頓。建議做兩件事:一是把「圖片檔名 → 表情文字」的對照表在啟動時就載入記憶體並建立 NSData 的快取字典,避免重複讀檔;二是把整段轉換放到背景佇列執行,完成後回主線程更新 UI。
另外,iOS 15 之後也可以考慮改用 TextKit 2 或 NSImage NSTextAttachment 的新寫法;若要處理使用者輸入的 emoji,系統本身已直接支援,不需要走這套替換流程——這套方案主要還是為「自製表情圖」而設計的。