美文网首页IOS收藏UILabel
UILabel 实现图文混排

UILabel 实现图文混排

作者: pingui | 来源:发表于2016-02-25 17:49 被阅读1195次

很多应用类app都会显示出下载量以及评论条数,通常会有一个图标然后紧跟着一个数字,只需要一个 UILabel 就能实现这样的效果,废话不多说,直接看代码!!!!

#import "ViewController.h"

@interface ViewController ()
// 绑定插座变量
@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSAttributedString *commentAttr = [self creatAttrStringWithText:@"在这里设置文字" image:[UIImage imageNamed:@"topic_Comment"]];
    // UILabel 通过XIB画的
    _myLabel.attributedText = commentAttr;
}

// 实现图文混排的方法
- (NSAttributedString *) creatAttrStringWithText:(NSString *) text image:(UIImage *) image{
    
    // NSTextAttachment可以将图片转换为富文本内容
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    // 通过NSTextAttachment创建富文本
    // 图片的富文本
    NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    // 文字的富文本
    NSAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    
    NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] init];
    
    // 将图片、文字拼接
    // 如果要求图片在文字的后面只需要交换下面两句的顺序
    [mutableAttr appendAttributedString:imageAttr];
    [mutableAttr appendAttributedString:textAttr];
    
    return [mutableAttr copy];
}
@end

效果图:

图文混排效果图.png

说明:我给 UILabel 设置了背景色

相关文章

网友评论

    本文标题:UILabel 实现图文混排

    本文链接:https://www.haomeiwen.com/subject/wkoikttx.html