iOS技术文档No.7 AppKit_NSTextAttachment为富文本添加图片

NSTextAttachment是配合富文本NSAttributedString或NSMutableAttributedString使用的一个类,可以为我们的文字中添加图片
代码:

UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 20)];
    label1.textColor=[UIColor blackColor];
    [self.view addSubview:label1];
    //富文本
    NSString *message = @"这是一段测试文字";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:message attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc]initWithData:nil ofType:nil];
    UIImage *image = [UIImage imageNamed:@"image.png"];
    attachment.image = image;
    attachment.bounds = CGRectMake(0, 0, 20, 20);
    
    NSAttributedString *text = [NSAttributedString attributedStringWithAttachment:attachment];
    [str insertAttributedString:text atIndex:5];
    
    label1.attributedText = str;

显示效果.png

但是我觉得系统这个添加图片的方法还不足够满足我们的需要,事实上我们在开发中可能不仅仅需要添加一个图片,例如在我们的攻略中可能有一个显示商品的视图,视图上面又有图片又有文字,这里我推荐大家看下 YYKit:

iOS技术文档No.7 AppKit_NSTextAttachment为富文本添加图片_第1张图片
发帖.png

上图是我在开发公司项目时写的一个demo,可以添加自定义的视图,demo没整理,写的很乱,所以就不上传了,如果有需要的可以留言给我。
YYkit中有一个方法可以把自定义的视图返回为NSMutableAttributedString:

+ (NSMutableAttributedString *)yy_attachmentStringWithContent:(id)content
                                                  contentMode:(UIViewContentMode)contentMode
                                               attachmentSize:(CGSize)attachmentSize
                                                  alignToFont:(UIFont *)font
                                                    alignment:(YYTextVerticalAlignment)alignment

这个方法允许我们传自定义的视图进去,这样一来问题就变得简单了

NSMutableAttributedString *attachText=[NSMutableAttributedString yy_attachmentStringWithContent:liwuView contentMode:UIViewContentModeScaleAspectFit attachmentSize:liwuView.frame.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];

你可能感兴趣的:(iOS技术文档No.7 AppKit_NSTextAttachment为富文本添加图片)