If the sizeWithFont:constrainedToSize:lineBreakMode:
method is deprecated in iOS7, how can I automatically resize a UILabel
to dynamically adjust its height and width to fit the text?
问问题
8467 次
2 回答
8
我最终使用了这个。为我工作。这不适用于 IBOutlets 对象,但在动态计算 uitableview 的 heightForRowAtIndexPath: 方法上的文本高度时很有用。
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"FontName" size:15], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(263, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
于 2013-09-10T08:38:30.377 回答
6
这应该适用于 iOS6 和 iOS7,但会破坏您的标签约束(如果需要,您需要以编程方式将它们全部设置回来):
-(void)resizeHeightForLabel: (UILabel*)label {
label.numberOfLines = 0;
UIView *superview = label.superview;
[label removeFromSuperview];
[label removeConstraints:label.constraints];
CGRect labelFrame = label.frame;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect expectedFrame = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, 9999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
label.font, NSFontAttributeName,
nil]
context:nil];
labelFrame.size = expectedFrame.size;
labelFrame.size.height = ceil(labelFrame.size.height); //iOS7 is not rounding up to the nearest whole number
} else {
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
labelFrame.size = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, 9999)
lineBreakMode:label.lineBreakMode];
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
}
label.frame = labelFrame;
[superview addSubview:label];
}
将此方法添加到您的 viewController 并像这样使用它:
[self resizeHeightForLabel:myLabel];
//set new constraints here if needed
于 2013-09-21T14:50:11.960 回答