實際開發中遇到這樣的問題,商品名稱前面需要加上标簽,例如特賣,保稅,等等。幾個标簽,标簽是誰都是可變的。這就意味着我們的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以後在恢複一下寬度。否則會出現顯示不全的情況因為自動算寬不會将我們加的标簽算入寬度。