实际开发中遇到这样的问题,商品名称前面需要加上标签,例如特卖,保税,等等。几个标签,标签是谁都是可变的。这就意味着我们的label不能写死。要动态适应,这样就需要用到缩进算法,效果如下
首先标签需要通过bean中的字段来控制,是几个标签,缩进多少需要我们写一个缩进算法,首先我们需要区分是保税,还是特卖,还是都有:
//保税 特卖 缩进算法
int number = 0;
if (bean.bonded_flag + bean.goodsflag ==2) {
number = 2;
};
if (bean.bonded_flag + bean.goodsflag ==1) {
number = 1;
}
if (bean.bonded_flag + bean.goodsflag ==0) {
number = 0;
}
处理一个标签的情况:
// 一个标签
if (number == 1 || number == 2) {
ColorTags *colorTag = [[ColorTags alloc]initWithFrame:CGRectMake(0,0 , 35, 17)];
[_goodsTitle addSubview:colorTag];
if (bean.bonded_flag == 1) {
[colorTag updateView:@"保税"];
} else {
[colorTag updateView:@"特卖"];
}
NSMutableParagraphStyle *paraStyle01 = [[NSMutableParagraphStyle alloc] init];
paraStyle01.alignment = NSTextAlignmentLeft; //对齐
paraStyle01.headIndent = 0.0f;//行首缩进
paraStyle01.firstLineHeadIndent = 38;//首行缩进
paraStyle01.tailIndent = 0.0f;//行尾缩进
paraStyle01.lineSpacing = 2.0f;//行间距
NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:_goodsTitle.text attributes:@{NSParagraphStyleAttributeName:paraStyle01}];
_goodsTitle.attributedText = attrText;
}
处理两个标签的情况
// 两个标签
if (number == 2) {
ColorTags *colorTag1 = [[ColorTags alloc]initWithFrame:CGRectMake(43,0 , 35, 17)];
[_goodsTitle addSubview:colorTag1];
[colorTag1 updateView:@"特卖"];
NSMutableParagraphStyle *paraStyle02 = [[NSMutableParagraphStyle alloc] init];
paraStyle02.alignment = NSTextAlignmentLeft; //对齐
paraStyle02.headIndent = 0.0f;//行首缩进
// //参数:(字体大小17号字乘以2,34f即首行空出两个字符)
// CGFloat emptylen = _goodsTitle.font.pointSize * 2;
paraStyle02.firstLineHeadIndent = 90;//首行缩进
paraStyle02.tailIndent = 0.0f;//行尾缩进
paraStyle02.lineSpacing = 2.0f;//行间距
NSAttributedString *attrText1 = [[NSAttributedString alloc] initWithString:_goodsTitle.text attributes:@{NSParagraphStyleAttributeName:paraStyle02}];
_goodsTitle.attributedText = attrText1;
}
[_goodsTitle sizeToFit];
_goodsTitle.width = kScreenWidth - 150;
可以看到处理的核心就是属性字符串,这次我们主要用了缩进功能。当然属性字符串功能很强大,包括行间距,段间距的处理都可以通过属性字符串来实现。另外需要注意到最后这两行代码:
[_goodsTitle sizeToFit];
_goodsTitle.width = kScreenWidth - 150;
sizetofit是为了让字体只有一行的时候,字体不会上下居中。否则跟自定义的标签就会不在一行。显示出下面的效果:
注意sizetofit以后在恢复一下宽度。否则会出现显示不全的情况因为自动算宽不会将我们加的标签算入宽度。