目的 : 实现一句话中既有文字又有图片的功能.
图文混排又称富文本.
直接代码演示:
NSAttributedString+Emoji.h 中 :
1 #import <Foundation/Foundation.h> 2 3 @interface NSAttributedString (Emoji) 4 5 + (NSAttributedString *)emojiStringWithString:(NSMutableAttributedString *)emojiString; 6 7 @end
NSAttributedString+Emoji.m 中:
1 #import "NSAttributedString+Emoji.h" 2 #import <UIKit/UIKit.h> 3 4 @interface EmojiAttachment : NSTextAttachment 5 6 @end 7 8 @implementation EmojiAttachment 9 10 - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex 11 { 12 return CGRectMake( 0 , -3, lineFrag.size.height, lineFrag.size.height); 13 } 14 15 @end 16 17 18 @implementation NSAttributedString (Emoji) 19 20 + (NSAttributedString *)emojiStringWithString:(NSMutableAttributedString *)emojiString 21 { 22 NSRegularExpression *regularEx = [NSRegularExpression regularExpressionWithPattern:@"m[0-9]{3}" options:NSRegularExpressionCaseInsensitive error:nil]; 23 24 NSString *string = emojiString.string; 25 26 NSTextCheckingResult *result = [regularEx firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)]; 27 if (result != nil) { 28 NSString *imageName = [NSString stringWithFormat:@"%@.png", [string substringWithRange:result.range]]; 29 EmojiAttachment *attachment = [[EmojiAttachment alloc] initWithData:nil ofType:nil]; 30 attachment.image = [UIImage imageNamed:imageName]; 31 NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachment]; 32 33 [emojiString replaceCharactersInRange:result.range withAttributedString:attrString]; 34 // 递归 35 [self emojiStringWithString:emojiString]; 36 } else { 37 return emojiString; 38 } 39 return emojiString; 40 }
在控制器中:
1 NSString *string = @"菲尼模式的博客,m006m008 图文混排又称富文本m010 !!! 菲尼模式的博客,m006m008 图文混排又称富文本m010!!!菲尼模式的博客,m006m008 图文混排又称富文本m010!!!"; 2 self.myLabel.attributedText = [NSAttributedString emojiStringWithString:[[NSMutableAttributedString alloc]initWithString:string]]; 3 self.myLabel.font = [UIFont boldSystemFontOfSize:23];
直接把.m 和.h文件放入工程中即可使用.
实现效果 :
时间: 2024-12-12 05:56:17