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

luc*_*uca 12 resize deprecated uilabel ios7

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

Joh*_*oza 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;
Run Code Online (Sandbox Code Playgroud)


Den*_*ovs 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];
}
Run Code Online (Sandbox Code Playgroud)

将此方法添加到viewController并使用它如下:

[self resizeHeightForLabel:myLabel];
//set new constraints here if needed
Run Code Online (Sandbox Code Playgroud)