如果标签包含 NSAttributed 字符串且部分字符串以粗体显示,如何获取标签的准确高度
我目前正在使用以下方法来获取标签所需的高度,
+ (CGFloat) getHeightOfLabel:(NSString *)text ofFontSize:(CGFloat)fontSize withConstraint:(CGSize)constraint
{
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
return size.height;
}
这在大多数情况下都有效,但是,有些字符串由粗体和非粗体文本混合组成,这可能会影响极端情况下所需的确切高度。
例如
有没有办法获得包含此混合物的标签的准确高度?
I am currently using the following method to get the required height of the label
+ (CGFloat) getHeightOfLabel:(NSString *)text ofFontSize:(CGFloat)fontSize withConstraint:(CGSize)constraint
{
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
return size.height;
}
This works in most cases, however, there are some strings which consist a mixture of bold and unbold text which might affect the exact height required in extreme cases.
For example
Are there any ways to get the accurate height of the label containing this mixture?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法如下
Here's how
我也在为此苦苦挣扎。这里有一些想法:
使用boldSystemFontOfSize来计算高度,因为它将允许最大空间(在大多数情况下,这是最糟糕的情况。有些标签会比需要的高一点,但我发现这比被切断要好。)
计算 systemFontOfSize 和 boldSystemFontOfSize 之间的平均值
如果您不需要实际高度,请使用 [label sizeToFit] 但我假设您需要这个高度:)
I was struggling with this as well. Here are a couple ideas:
Use boldSystemFontOfSize to calculate the height since it will allow for maximum room (In most cases, this worst well. Some labels will be a little taller than needed but I find it's better than getting cut off.)
Calculate the average between systemFontOfSize and boldSystemFontOfSize
If you don't need the actual height use [label sizeToFit] but I'm assuming you need this height :)