代碼如下:
UILabel *label = [[UILabel alloc] init];
label.text = labText;
CGFloat width = label.frame.size.width; //width : UILable的寬度
CGSize size = CGSizeMake(width, MAXFLOAT);
CGFloat wordSize = 17; //wordSize : 文字的大小
UIFont *font = [UIFont systemFontOfSize:wordSize];
//自動換行
self.numberOfLines = 0;
CGSize textRealSize;
if (iOS7) { //iOS7以后的版本么夫,包括iOS7
textRealSize = [self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
} else { //iOS7以前的版本
textRealSize = [self.text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
}
//改變高度
CGRect rect = label.frame;
rect.size.height = textRealSize.height;
label.frame = rect;