使用sizeWithFont调整UILabel的大小:constrainedToSize:lineBreakMode:iOS7中不推荐使用

时间:2013-09-06 15:10:09

标签: resize uilabel deprecated ios7

如果在iOS7中弃用了sizeWithFont:constrainedToSize:lineBreakMode:方法,如何自动调整UILabel的大小以动态调整其高度和宽度以适合文本?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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