UILabel插入图片简单操作

UILabel插入图片简单操作


1.需求

image.png

2.解决方案

UILabel有attributedString属性. NSAttributedString有NSTextAttachment属性可以支持在文本中插入附件 ** 例如图片 ** .从而达到在文本中插入图片的效果

3.代码

//初始化
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
//空格间隙
    NSAttributedString *spaceString = [[NSAttributedString alloc] initWithString:@" "];
//图片
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
            attachment.image = image;
            attachment.bounds = CGRectMake(0, -3, 19, 19);
            NSAttributedString *imageAttachment = [NSAttributedString attributedStringWithAttachment:attachment];
            //图片
            [attributedString appendAttributedString:imageAttachment];
            //空格间隙
            [attributedString appendAttributedString:spaceString];
//文字
NSMutableAttributedString *textString = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange textRange = NSMakeRange(0, text.length);
    //行间距
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    style.lineSpacing = 5;
    [textString addAttribute:NSParagraphStyleAttributeName value:style range:textRange];
    //文字颜色
    [textString addAttribute:NSForegroundColorAttributeName value:textColor range:textRange];
    //字体
    [textString addAttribute:NSFontAttributeName value:textFont range:textRange];

4.为什么需要空格间隙

因为插入图片之后,文字会紧贴着图片.NSTextAttachment设置的bounds是图片的大小,没有设置间隙的属性,所以就用个空格去代替间隙

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容