#import <UIKit/UIKit.h> @interface UILabel (dynamicSize) -(float)resizeToFit; -(float)expectedHeight; @end
#import "UILabel+dynamicSize.h"
@implementation UILabel (dynamicSize)
-(float)resizeToFit{
float height = [self expectedHeight];
CGRect newFrame = [self frame];
newFrame.size.height = height;
[self setFrame:newFrame];
return newFrame.origin.y + newFrame.size.height;
}
-(float)expectedHeight{
[self setNumberOfLines:0];
[self setLineBreakMode:NSLineBreakByCharWrapping];
UIFont *font = [UIFont systemFontOfSize:14.0];
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
font, NSFontAttributeName,
nil];
CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,9999);
CGRect expectedLabelRect = [[self text] boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:attributesDictionary
context:nil];
CGSize *expectedLabelSize = &expectedLabelRect.size;
return expectedLabelSize->height + self.frame.size.height;
}
@end- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 150, 35)];
label.backgroundColor = [UIColor lightGrayColor];
label.text = @"This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.hahhaha";
CGRect newRect = label.frame;
newRect.size.height = [label expectedHeight];
label.frame = newRect;
[self.view addSubview:label];
}原文地址:http://blog.csdn.net/chaoyuan899/article/details/41682013