sizeWithFont:constrainedToSize:lineBreakMode:不准确? [英] sizeWithFont:constrainedToSize:lineBreakMode: not accurate?

查看:88
本文介绍了sizeWithFont:constrainedToSize:lineBreakMode:不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sizeWithFont:constrainedToSize:lineBreakMode:似乎没有给我返回正确的宽度。执行这些代码后,我看到标签中的部分字符串正在切断,这意味着我要手动添加几个像素的大小。我错过了什么吗?

sizeWithFont:constrainedToSize:lineBreakMode: don't seem to be returning me the correct width. After these codes are executed, I see that part of the string in the label is chopping off, which means I've to manually add a few pixels to the size. Am I missing something?

我有一个UILabel:

I've a 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];

我尝试使用以下方法以编程方式修改标签的大小:

I tried to programmatically modify the size of the label using the following:

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;


推荐答案

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

Ok, well, the first thing I'll say is that there are some very useful ways to deal with frames that you currently aren't employing. For example, your code,

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);

但是,如果您的代码按预期工作,则根本不需要执行此操作。你可以去两条路线,

However, if your code worked as it was intended, you would not need to do this at all. You can go two routes,

[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

No where in your earlier code did you change the width of theLabel to match the expected width. Notice, you wrote newFrame.size.width = newFrame.size.width+50 and that should be newFrame.size.width = expectedLabelSize.width.

这篇关于sizeWithFont:constrainedToSize:lineBreakMode:不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆