OC: UILabel+MaxMethod

.h文件

#import 

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

.m文件

#import "UILabel+MaxMethod.h"
#import 

@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

你可能感兴趣的:(OC: UILabel+MaxMethod)