原文:https://www.jianshu.com/p/2b1620944a90
效果如下:
image.png
给UILabel写一个分类:
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UILabel (AutoSpace)
//两端对齐
- (void)textAlignmentLeftAndRight;
- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth;
@end
NS_ASSUME_NONNULL_END
#import "UILabel+AutoSpace.h"
#import <CoreText/CoreText.h>
@implementation UILabel (AutoSpace)
- (void)textAlignmentLeftAndRight {
[self textAlignmentLeftAndRightWith:CGRectGetWidth(self.frame)];
}
- (void)textAlignmentLeftAndRightWith:(CGFloat)labelWidth {
if (self.text == nil || self.text.length == 0) {
return;
}
CGSize size = [self.text boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
NSInteger length = (self.text.length - 1);
NSString *lastStr = [self.text substringWithRange:NSMakeRange(self.text.length - 1,1)];
if ([lastStr isEqualToString:@":"] || [lastStr isEqualToString:@":"]) {
length = (self.text.length - 2);
}
CGFloat margin = (labelWidth - size.width) / length;
NSNumber *number = [NSNumber numberWithFloat:margin];
NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc]initWithString:self.text];
[attribute addAttribute:NSKernAttributeName value:number range:NSMakeRange(0, length)];
self.attributedText = attribute;
}
@end
在设置完label的frame、text、font等属性后再调用:
[myLabel textAlignmentLeftAndRight];
网友评论