resize - 在ios中,使用 sizeWithFont: constrainedToSize: lineBreakMode: 调整UILabel大小

  显示原文与译文双语对照的内容
0 0

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

时间:原作者:7个回答

0 0

我都用这个了。 我就吃这套 完成上步骤后不起作用,但是uitableview上有用,在计算动态文本的高度是heightForRowAtIndexPath IBOutlets对象: 方法。

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;
原作者:
0 0

这应该工作在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
原作者:
...