我为 UILabels 创建了一个处理高度的类别:
UILabel+TCFlexibleHeight.h:
#import <UIKit/UIKit.h>
@interface UILabel (TCFlexibleHeight)
- (CGFloat)heightForText:(NSString*)text;
- (CGFloat)heightForCurrentText;
- (CGFloat)adjustHeightForCurrentText;
@end
UILabel+TCFlexibleHeight.m :
#import "UILabel+TCFlexibleHeight.h"
static const NSInteger kMaxLines = 1000;
@implementation UILabel (TCFlexibleHeight)
- (CGFloat)heightForText:(NSString*)text {
if (text == nil) {
return 0;
}
NSInteger numberOfLines = self.numberOfLines > 0 ? self.numberOfLines : kMaxLines;
CGSize size = CGSizeMake(self.frame.size.width, self.font.lineHeight * numberOfLines);
return [text sizeWithFont:self.font constrainedToSize:size lineBreakMode:self.lineBreakMode].height;
}
- (CGFloat)heightForCurrentText {
return [self heightForText:self.text];
}
- (CGFloat)adjustHeightForCurrentText {
CGFloat height = [self heightForCurrentText];
CGRect frame = self.frame;
frame.size.height = height;
return height;
}
@end
使用此类别,您的代码将如下所示:
[themeLabel setFrame:CGRectMake(leftMargin, mainScrollView.frame.origin.y + topPadding, 274, [themeLabel heightForCurrentText])];
请注意,此类别不处理属性字符串,并且需要将换行设置为剪辑到字符。