在項目中遇到兩個等高寬的UILabel,一個文字2個字,另一個4個字。這時候排版要求是2個字是居左居右排版,
查看了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
沒有找到左右的屬性。
寫一個Category,利用#import <CoreText/CoreText.h>對文字進行處理。
#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;
//計算字間距
CGFloat margin = (self.frame.size.width - textSize.width) / (self.text.length - 1);
NSNumber *number = [NSNumber numberWithFloat:margin];
//修改默認字間距離
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:self.text];
[attributeString addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, self.text.length -1 )];
self.attributedText = attributeString;
}
@end
實現結果
Paste_Image.png
Paste_Image.png