iOS-文字左右对齐

在项目中遇到两个等高宽的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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容