開發(fā)中常遇到UI要求文本均勻分布,兩端對(duì)齊,開始使用在文字中手動(dòng)打空格的方式,但常常會(huì)碰到相同文字有時(shí)三個(gè)字,有時(shí)四個(gè)字,五個(gè)字,這個(gè)時(shí)候用打空格的方式就會(huì)出現(xiàn)最后面的字或者符號(hào)無法對(duì)齊。此時(shí),可以采用Category對(duì)UILable的文字分布方式進(jìn)行處理
創(chuàng)建一個(gè)Category,.h提供方法
//兩端對(duì)齊
- (void)textAlignmentLeftAndRight;
//指定Label以最后的冒號(hào)對(duì)齊的width兩端對(duì)齊
- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;
.m中實(shí)現(xiàn)
引用
#import <CoreText/CoreText.h>
- (void)textAlignmentLeftAndRight{
[self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];
}
- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth{
if(self.text==nil||self.text.length==0) {
return;
}
CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
NSInteger length = (self.text.length-1);
NSString* lastStr = [self.text substringWithRange:NSMakeRange(self.text.length-1,1)];
if([lastStr isEqualToString:@":"]||[lastStr isEqualToString:@":"]) {
length = (self.text.length-2);
}
CGFloat margin = (labelWidth - size.width)/length;
NSNumber*number = [NSNumber numberWithFloat:margin];
NSMutableAttributedString* attribute = [[NSMutableAttributedString alloc]initWithString:self.text];[attributeaddAttribute:NSKernAttributeName value:numberrange:NSMakeRange(0,length)];
self.attributedText= attribute;
}
使用時(shí)應(yīng)注意要在給Lable的frame,text設(shè)置完之后再使用,默認(rèn)使用textAlignmentLeftAndRight即可。若有其他指定寬度要設(shè)置,可使用- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;? 若結(jié)尾文字以其他固定文字結(jié)尾,可替換冒號(hào)再使用
具體效果如下