UILabel+ContentSize.h
#import <UIKit/UIKit.h>
@interface UILabel (ContentSize)
- (CGSize)contentSize;
@end
UILabel+ContentSize.m
#import "UILabel+ContentSize.h"
@implementation UILabel (ContentSize)
- (CGSize)contentSize {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = self.lineBreakMode;
paragraphStyle.alignment = self.textAlignment;
NSDictionary * attributes = @{NSFontAttributeName : self.font,
NSParagraphStyleAttributeName : paragraphStyle};
CGSize contentSize = [self.text boundingRectWithSize:self.frame.size
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil].size;
return contentSize;
}
本文介绍了一个UILabel的分类扩展,用于自动计算UILabel的内容尺寸。通过设置UILabel的字体、对齐方式和换行模式,该方法能返回UILabel实际所需的内容尺寸。
273

被折叠的 条评论
为什么被折叠?



