UILabel 实现图文混排
2016-02-25 本文已影响1195人
pingui
很多应用类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 设置了背景色