动态UILabel截断文本 [英] Dynamic UILabel truncating the text

查看:165
本文介绍了动态UILabel截断文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此答案中提供的代码来创建动态标签,它可以正常工作在大多数情况下.但是,只要标签文本的长度超过94个字符,就会被截断并添加省略号.

I'm using code provided in this answer to create a dynamic label and it works for the most part. But whenever the label text goes over 94 characters in length it gets truncated and ellipsis' are added.

还有一个奇怪的事情是,如果我向字符串中添加更多字符,则会显示它们,但最后两行仍会被截断.

There is one more odd thing about this is that if I add more characters to the string they are shown but the last 2 lines are still truncated.

例如.

字符串:

this is a very very long string 
with lots of words to test the 
dynamic bubble sizing one two three.

显示如下:

this is a very very long string 
with lots of words to test the 
dynamic bubble sizing one tw...

但是当我再次在标签中使用相同的句子将字符串加倍时,它会显示更多文本,但仍会截断它.

But when I double the string by using the same sentence again in the label it show more of te text but still truncates it.

例如.

字符串:

this is a very very long string 
with lots of words to test the 
dynamic bubble sizing one two 
three. this is a very very long 
string with lots of words to test 
the dynamic bubble sizing one 
two three.

显示如下:

this is a very very long string 
with lots of words to test the 
dynamic bubble sizing one two 
three. this is a very very long 
string with lots of words to tes...

这是我正在使用的代码.

Here's the code I'm using.

NSString *temp = [NSString stringWithFormat:@"this is a very very long string with lots of words to test the dynamic bubble sizing one two three"];

captionLabel.text = temp;
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [temp sizeWithFont:captionLabel.font 
                                  constrainedToSize:maximumLabelSize 
                                      lineBreakMode:captionLabel.lineBreakMode]; 

//adjust the label the the new height.
CGRect newFrame = captionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
captionLabel.frame = newFrame; 

希望有人有一个主意,因为这让我挠头.

Hope someone has an idea because this has me scratching my head.

编辑

由于使用了@troolee,因此使用captionLabel.frame.size.width而不是硬编码296对其进行了修复,如果他/她选择创建答案,则将其标记为正确.

Using captionLabel.frame.size.width instead of hard-coded 296 fixed it, thanks to @troolee, if he/she chooses to create an answer I will mark it correct.

推荐答案

我希望@troolee现在可以将他的评论作为答案,但是由于他没有,我将发布答案并将其标记为正确,所以我可以解决这个问题.

I was hoping @troolee would have made his comment an answer by now but since he hasn't I'm going to post the answer and mark it correct so I can close off this question.

使用captionLabel.frame.size.width而不是硬编码296对其进行修复.

Using captionLabel.frame.size.width instead of hard-coded 296 fixed it.

这篇关于动态UILabel截断文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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