iOS-文字左右對齊

在項(xiàng)目中遇到兩個(gè)等高寬的UILabel,一個(gè)文字2個(gè)字,另一個(gè)4個(gè)字。這時(shí)候排版要求是2個(gè)字是居左居右排版,

查看了UILabel的textAlignment屬性有

NSTextAlignmentLeft      = 0,    // Visually left aligned
NSTextAlignmentCenter    = 1,    // Visually centered
NSTextAlignmentRight     = 2,    // Visually right aligned
NSTextAlignmentRight     = 1,    // Visually right aligned
NSTextAlignmentCenter    = 2,    // Visually centered
NSTextAlignmentJustified = 3,    // Fully-justified. The last line in a paragraph is natural-aligned.
NSTextAlignmentNatural   = 4,    // Indicates the default alignment for script

沒有找到左右的屬性。

寫一個(gè)Category,利用#import <CoreText/CoreText.h>對文字進(jìn)行處理。


#import "UILabel+AlignmentMethod.h"
#import <CoreText/CoreText.h>

@implementation UILabel (AlignmentMethod)

- (void)alignmentMethodLeftAndRight {
    [self layoutIfNeeded];

    CGSize textSize = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading
                                           attributes:@{NSFontAttributeName :self.font}
                                              context:nil].size;
    
    //計(jì)算字間距
    CGFloat margin = (self.frame.size.width - textSize.width) / (self.text.length - 1);
    NSNumber *number = [NSNumber numberWithFloat:margin];
    
    //修改默認(rèn)字間距離
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attributeString addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, self.text.length -1 )];
    self.attributedText = attributeString;
}
@end

實(shí)現(xiàn)結(jié)果

Paste_Image.png
Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容