【问题标题】:iPhone how to identify whether UILabels will show truncated text?iPhone如何识别UILabels是否会显示截断的文本?
【发布时间】:2012-08-27 12:18:27
【问题描述】:

UILineBreakModeTailTruncation 启动时,我需要在UILabel 上显示更多按钮。即,每当“...”出现时,我需要通过一些操作显示我的更多按钮。

我正在做的是

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

但我的问题是,当标签的行数设置为 2 时,每当呈现标签的第一行时,就会显示更多按钮。

所以我试过了

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

这在大多数情况下都有效。但在某些文本宽度与 2* labelsWidth 相同的情况下,会显示更多按钮。有什么直接的方法吗?

【问题讨论】:

    标签: objective-c ios uibutton uilabel


    【解决方案1】:

    尝试 constrainedToSize 变体:

    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】:

      与字符串的高度比较,因为宽度相同:

      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】:

        你可以使用这个函数来获取字符串的大小:

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

        您还应该检查其他 sizeWithFont: 函数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-07
          • 2021-05-26
          • 2019-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多