OC: UILabel+MaxMethod

2018-11-06  本文已影响5人  一欧Yiou

.h文件

#import <UIKit/UIKit.h>

@interface UILabel (MaxMethod)
// 设置UILabel两端对齐
- (void)changeAlignmentRightandLeft;
@end

.m文件

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

@implementation UILabel (MaxMethod)
- (void)changeAlignmentRightandLeft {
    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
上一篇 下一篇

猜你喜欢

热点阅读