iphone - 如何计算 UILabel 可以包含的 NSString 最大长度而不截断文本?

标签 iphone ios xcode nsstring uilabel

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

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

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

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

最佳答案

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

+ (int)getSplitIndexWithString:(NSString *)str frame:(CGRect)frame andFont:(UIFont *)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/

相关文章:

ios - 在不为后退滑动按钮设置动画的情况下呈现警报

ios - 带有复选标记的 UITableViewCell,复制复选标记

ios - 如何在选择器中传递自定义 UITableViewCell

iphone - 在 Facebook 中点击 Facebook 登录 View 的登录对话框时键盘不会出现,例如 Delegate

iphone - 在photoscroller应用程序(iPhone WWDC-104照片应用程序)中,使用presentModalviewController调用时,uiscrollview图像向右移动

iphone - 检索 UIImage 的像素 alpha 值

iphone - Apple 推送通知出现文件丢失错误

iphone - 程序员之间是否可以共享 Apple Developer Program 许可证?

ios - ALL 或 ANY 运算符的左侧必须是 NSArray 或 NSSet

javascript - OS X 和 iOS Safari history.replaceState 限制抛出 SecurityError : DOM Exception 18