NSTextAttachment的简单应用

效果图

NSTextAttachment的简单应用_第1张图片
WX20171114-103538.png
    NSString *tmpStr = @"测试后面有没有图片测试后面有没有图片测试后面有没有图片[图片]";
    
    UIFont *font = [UIFont systemFontOfSize:16];
    CGFloat imageHeight = font.lineHeight;

    // 设置图片附件
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    textAttachment.image = image;
    // 调整一下图片的位置,如果你的图片偏上或者偏下,调整一下bounds的y值即可
    textAttachment.bounds = CGRectMake(0, -2, imageHeight, imageHeight);

    NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
    
    NSMutableAttributedString *mStr = [[NSMutableAttributedString alloc] initWithString:tmpStr];
    
    NSRange range = [tmpStr rangeOfString:@"[图片]"];
    [mStr replaceCharactersInRange:range withAttributedString:imageStr];
    
    self.label.attributedText = mStr;

你可能感兴趣的:(NSTextAttachment的简单应用)