OGeek|极客世界-中国程序员成长平台

标题: iphone - 如何计算 UILabel 可以包含的 NSString 最大长度而不截断文本? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:45
标题: iphone - 如何计算 UILabel 可以包含的 NSString 最大长度而不截断文本?

我有两个 UILabel,一个在另一个之上。 顶部有固定大小(2 行),底部可以扩展(0 行)。 我用于标签的文本可能很短,有时可能很长。 如何计算第一个 UILabel 最大字符串长度而不在中间切一个单词?

//这里是创建两个标签的代码。

    titleView = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 200, 50)]; 
    titleView.numberOfLines = 2;

    titleView2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 250, 100)];
    titleView2.numberOfLines = 0;



Best Answer-推荐答案


我已经用这个方法解决了问题:

+ (int)getSplitIndexWithStringNSString *)str frameCGRect)frame andFontUIFont *)font
{
    int length = 1;
    int lastSpace = 1;
    NSString *cutText = [str substringToIndex:length];
    CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
      while (textSize.height <= frame.size.height)
      {
          NSRange range = NSMakeRange (length, 1);
          if ([[str substringWithRange:range] isEqualToString" "])
          {
              lastSpace = length;
          }
          length++;
          cutText = [str substringToIndex:length];
          textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
      }
      return lastSpace;
}

关于iphone - 如何计算 UILabel 可以包含的 NSString 最大长度而不截断文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9965474/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4