- (NSAttributedString *)emojiAttributedString:(NSString *)string withFont:(UIFont *)font
{
NSMutableAttributedString *parsedOutput = [[NSMutableAttributedString alloc]initWithString:string attributes:@{NSFontAttributeName : font}];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]" options:0 error:nil];
NSArray* matches = [regex matchesInString:[parsedOutput string]
options:NSMatchingWithoutAnchoringBounds
range:NSMakeRange(0, parsedOutput.length)];
NSDictionary *emojiPlistDic = [[NSDictionary alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"emojiNew" ofType:@"plist"]];
// Make emoji the same size as text
CGSize emojiSize = CGSizeMake(font.lineHeight, font.lineHeight);
for (NSTextCheckingResult* result in [matches reverseObjectEnumerator]) {
NSRange matchRange = [result range];
// Find emoji images by placeholder
NSString *placeholder = [parsedOutput.string substringWithRange:matchRange];
NSLog(@"olaceholder:%@",placeholder);
UIImage *emojiImage = [UIImage imageNamed:emojiPlistDic[placeholder]];
// Resize Emoji Image
UIGraphicsBeginImageContextWithOptions(emojiSize, NO, 0.0);
[emojiImage drawInRect:CGRectMake(0, 0, emojiSize.width, emojiSize.height)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSTextAttachment *textAttachment = [NSTextAttachment new];
textAttachment.image = resizedImage;
// Replace placeholder with image
NSAttributedString *rep = [NSAttributedString attributedStringWithAttachment:textAttachment];
[parsedOutput replaceCharactersInRange:matchRange withAttributedString:rep];
}
return [[NSAttributedString alloc]initWithAttributedString:parsedOutput];
}
表情的文字都是中文,如果只有一个字的时候就没有问题,像第三个,如果有两个字,就会有空格。请问怎么去掉这个空格?
[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];