sizeWithFont:constrainedToSize:lineBreakMode 不准确?

3
sizeWithFont:constrainedToSize:lineBreakMode: 看起来没有返回正确的宽度。执行这些代码后,我发现标签中的字符串部分被截断了,这意味着我必须手动添加一些像素到大小中。我错过了什么吗?
我有一个UILabel:
theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LABELWIDTH, LABELHEIGHT)];
theLabel.lineBreakMode = UILineBreakModeWordWrap;
theLabel.numberOfLines = 0;
[theLabel setFont:[UIFont fontWithName:@"MarkerFelt-Wide" size:16]];
theLabel.textColor = [UIColor blackColor];
theLabel.textAlignment =  UITextAlignmentLeft;
theLabel.backgroundColor = [UIColor clearColor];

我尝试使用以下代码来以编程方式修改标签大小:

CGSize maximumLabelSize = CGSizeMake(LABELWIDTH, 10000);

CGSize expectedLabelSize = [someString sizeWithFont:theLabel.font constrainedToSize:maximumLabelSize lineBreakMode:theLabel.lineBreakMode];

theLabel.text = someString;

CGRect newFrame = theLabel.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = newFrame.size.width+50;
theLabel.frame = newFrame;

1
首先,someTextsomeString应该是相同的。它们指向同一个NSString吗? - john
是的,它们是。我进行了更改以使其更清晰。 - tommi
这是否在 UITableViewCell 中? - john
嗨@Mr. Berna,我正在尝试使用sizeToFit,但我仍然不确定为什么标签的大小总是较小,从而截断了其中一部分文本。有任何想法吗? - tommi
1个回答

1

好的,首先我要说的是,有一些非常有用的方法来处理框架,你目前没有使用。例如,你的代码:

CGRect newFrame = theLabel.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = newFrame.size.width+50;
theLabel.frame = newFrame;

可以使用CGGeometry中的函数进行重写。

CGFloat widthOffset = 50.0f;
theLabel.frame = CGRectOffset(CGRectInset(theLabel.frame, widthOffset, 0.0f), widthOffset / 2.0f, 0.0f);

然而,如果您的代码按照预期工作,您根本不需要这样做。您可以选择两种路线,

[theLabel sizeToFit];

或者,这个也应该可以工作,

theLabel.frame = CGRectMake(theLabel.frame.origin.x, theLabel.frame.origin.y, expectedLabelSize.width, expectedLabelSize.height);

在您之前的代码中,没有改变theLabel的宽度以匹配预期的宽度。请注意,您编写了newFrame.size.width = newFrame.size.width+50,应该是newFrame.size.width = expectedLabelSize.width

我正在尝试使用sizeToFit,但我仍然不确定为什么标签的大小总是较小,从而截断了文本的一部分。有什么想法吗? - tommi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接