iPhone how to identify whether UILabels will show truncated text?

做~自己de王妃 提交于 2019-12-13 18:53:07

问题


I need to show a more button on my UILabel when UILineBreakModeTailTruncation starts. ie whenever the "..." appears, I need to display my more button with some actions.

What I am doing is

float textWidth = [myString sizeWithFont:myLabel.font].width;
if (textWidth > myLabel.frame.size.width)
{
[moreButton setHidden:FALSE];
}
else
{
[moreButton setHidden:TRUE];
}

But my problem is, when the number of lines of the label is set to 2, more button is shown whenever the first line of the label is rendered.

So I have tried

if (textWidth > 2*myLabel.frame.size.width)
{
[moreButton setHidden:FALSE];
}
else
{
[moreButton setHidden:TRUE];
}

This works in most cases. But in some cases where text width is same as that of 2* labelsWidth, more button is shown. Is there any direct method to this?


回答1:


try the constrainedToSize variant:

CGSize maxSize = CGSizeMake (myLabel.frame.size.width, 9999);  // a really tall frame

// this will give you the actual size of your string
CGSize actualSize = [myString sizeWithFont:myLabel.font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];

if (actualSize.height > myLabel.frame.size.height)
{
 // show your more button
}



回答2:


Compare with height of string as width is will be same:

CGSize maximumSize = CGSizeMake(myLabel.frame.size.width, 500); //provide fixed label's width as we will have have fit text in that width. I have used approximately. height can be anything more view' height so take like that
CGSize strSize = [str sizeWithFont:[UIFont systemFontSize] constrainedToSize:maximumSize lineBreakMode:UILineBreakModeCharacterWrap];

if(strSize.height > 40) //Calulate height of two lines...
{
  [moreButton setHidden:NO]; //more than 2 lines
}
else
{
   [moreButton setHidden:YES];//less than 2 lines
}
}



回答3:


You can use this function to get the size of the string:

CGSize size=[myLabel.text sizeWithFont:[UIFont systemFontOfSize:h] constrainedToSize:CGSizeMake(maxWidth, maxHeight) lineBreakMode:UILineBreakModeTailTruncation];

You should also check the other sizeWithFont: functions.



来源:https://stackoverflow.com/questions/12141853/iphone-how-to-identify-whether-uilabels-will-show-truncated-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!