.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
网友评论