iOS - UILabel展示包含图标的文字
2020-04-07 本文已影响0人
Joh蜗牛
方法:
将图片插入文字中。
代码:
NSMutableAttributedString * titleAttributedStr = [[NSMutableAttributedString alloc] init];
titleAttributedStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@ %@ %@",[NULLClass nullClass:goodsModel.data.productName],[NULLClass nullClass:goodsModel.data.materialName],[NULLClass nullClass:goodsModel.data.specName],[NULLClass nullClass:goodsModel.data.factoryName]]];
// 创建一个富文本
NSMutableAttributedString * attributedStr = [[NSMutableAttributedString alloc] init];
if ([goodsModel.data.isSelfShop integerValue] == 1) {
//自营
NSTextAttachment *nameTextAttach = [[NSTextAttachment alloc]init];
UIImage *img = [UIImage imageNamed:@"自营 H28"];
nameTextAttach.image = img;
nameTextAttach.bounds = CGRectMake(0, -2, 32, 19);
NSAttributedString * strA =[NSAttributedString attributedStringWithAttachment:nameTextAttach];
[attributedStr appendAttributedString:strA];
[attributedStr appendAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" "]]];
}
if ([goodsModel.data.flag integerValue] == 1) {
//特价商品
NSTextAttachment *nameTextAttach = [[NSTextAttachment alloc]init];
UIImage *img = [UIImage imageNamed:@"组 5428"];
nameTextAttach.image = img;
nameTextAttach.bounds = CGRectMake(0, -2, 39, 19);
NSAttributedString * strA =[NSAttributedString attributedStringWithAttachment:nameTextAttach];
[attributedStr appendAttributedString:strA];
[attributedStr appendAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" "]]];
}
if ([goodsModel.data.goodsType integerValue] == 2) {
// 厂发
NSTextAttachment *nameTextAttach = [[NSTextAttachment alloc]init];
UIImage *img = [UIImage imageNamed:@"common_cf"];
nameTextAttach.image = img;
nameTextAttach.bounds = CGRectMake(0, -2, 19, 19);
NSAttributedString * strA =[NSAttributedString attributedStringWithAttachment:nameTextAttach];
[attributedStr appendAttributedString:strA];
[attributedStr appendAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" "]]];
}
if ([goodsModel.data.consignmentStatus integerValue] == 1) {
//寄售
NSTextAttachment *nameTextAttach = [[NSTextAttachment alloc]init];
UIImage *img = [UIImage imageNamed:@"寄售 H28"];
nameTextAttach.image = img;
nameTextAttach.bounds = CGRectMake(0, -3, 36, 19);
NSAttributedString * strA =[NSAttributedString attributedStringWithAttachment:nameTextAttach];
[attributedStr appendAttributedString:strA];
[attributedStr appendAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" "]]];
}
[attributedStr appendAttributedString:titleAttributedStr];
self.goodsNameLabel.attributedText = attributedStr;