我有一个标签,我以编程方式创建和显示。它可以是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
会返回宽度足以适合整个字符串的大小,即使它大于{{1}的宽度}。
我可以通过检查maxLabelSize
是否大于requiredSize.width
并进行适当调整来解决此问题,但我想知道为什么maxLabelSize.width
的行为与1行标签比使用多行标签。我希望大小不超过200,高度与属性字符串的行高相同。
答案 0 :(得分:2)
我不知道sizeThatFits
为什么不起作用,但另一种方法textRectForBounds:limitedToNumberOfLines:可以解决问题。像
label.numberOfLines = 0;
CGSize requiredSize = [label textRectForBounds:CGRectMake(0, 0, 200, CGFLOAT_MAX) limitedToNumberOfLines:1].size;
答案 1 :(得分:0)
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;