UILabel sizeThatFits 对于 1 行标签来说太宽了

UILabel sizeThatFits too wide for 1-line label

我有一个以编程方式创建和显示的标签。它可以是 1 行或多行。如果标签太长,我希望标签在末尾被截断。当标签的长度 > 1 行时,以下代码可以正常工作。创建一个空白项目并将其放入 viewDidLoad 以在家里一起玩。任何 iOS 或 tvOS 项目都可以。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.numberOfLines = 2;
label.lineBreakMode = NSLineBreakByTruncatingTail;
label.backgroundColor = [UIColor blueColor];
[self.view addSubview:label];

NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:26.0]};

label.attributedText = [[NSAttributedString alloc] initWithString:@"The rain in Spain falls mainly on the plain." attributes:attributes];

CGSize maxLabelSize = CGSizeMake(200, CGFLOAT_MAX);
CGSize requiredSize = [label sizeThatFits:maxLabelSize];
NSLog(@"requiredSize: %@", NSStringFromCGSize(requiredSize));
label.frame = CGRectMake(50.0, 50.0, requiredSize.width, requiredSize.height);

但是,如果我将 numberOfLines 更改为 1,则 sizeThatFits returns 的宽度足以容纳整个字符串,即使它大于 [= 的宽度14=].

我可以通过检查 requiredSize.width 是否大于 maxLabelSize.width 并适当调整来解决这个问题,但我想知道为什么 sizeThatFits 的行为与1 行标签比多行标签好。我希望大小不超过 200,高度与属性字符串的行高相同。

我不知道为什么 sizeThatFits 不起作用,但另一种方法 textRectForBounds:limitedToNumberOfLines: 可以解决问题。像

label.numberOfLines = 0;
CGSize requiredSize = [label textRectForBounds:CGRectMake(0, 0, 200, CGFLOAT_MAX) limitedToNumberOfLines:1].size;

UILabel * commlbl;

commlbl=[[UILabel alloc]initWithFrame:CGRectMake(10, commlbl1.bounds.size.height+50, commscroll.bounds.size.width-25, commscroll.bounds.size.height+70)];
[commlbl setFont:[UIFont fontWithName:@"OpenSans-Regular" size:16]];
[commlbl setTextColor:[UIColor whiteColor]];
[commlbl setTextAlignment:NSTextAlignmentCenter];
commlbl.lineBreakMode = NSLineBreakByWordWrapping;
commlbl.numberOfLines = 0;
commlbl.text = [USER_DFT GetUserDefault:@"msgString"];
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [commlbl.text sizeWithFont:commlbl.font constrainedToSize:maximumLabelSize lineBreakMode:commlbl.lineBreakMode];
    //adjust the label the the new height.
CGRect newFrame = commlbl.frame;
newFrame.size.height = expectedLabelSize.height;
commlbl.frame = newFrame;