iOS開發(fā),UILabel文字均勻分布,兩端對(duì)齊鋪滿整個(gè)控件

開發(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)再使用

具體效果如下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容