很多應(yīng)用類app都會(huì)顯示出下載量以及評(píng)論條數(shù)浊竟,通常會(huì)有一個(gè)圖標(biāo)然后緊跟著一個(gè)數(shù)字,只需要一個(gè) UILabel 就能實(shí)現(xiàn)這樣的效果,廢話不多說浅萧,直接看代碼V鹕场!M莩吩案!
#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:@"在這里設(shè)置文字" image:[UIImage imageNamed:@"topic_Comment"]];
// UILabel 通過XIB畫的
_myLabel.attributedText = commentAttr;
}
// 實(shí)現(xiàn)圖文混排的方法
- (NSAttributedString *) creatAttrStringWithText:(NSString *) text image:(UIImage *) image{
// NSTextAttachment可以將圖片轉(zhuǎn)換為富文本內(nèi)容
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = image;
// 通過NSTextAttachment創(chuàng)建富文本
// 圖片的富文本
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 設(shè)置了背景色