美文网首页
OC: UILabel+MaxMethod

OC: UILabel+MaxMethod

作者: 一欧Yiou | 来源:发表于2018-11-06 14:58 被阅读5次

.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

相关文章

网友评论

      本文标题:OC: UILabel+MaxMethod

      本文链接:https://www.haomeiwen.com/subject/gdhuxqtx.html