问题
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