【问题标题】:Find the correct font size for a given text in OBJ C?在 OBJ C 中为给定文本找到正确的字体大小?
【发布时间】:2017-11-23 16:53:27
【问题描述】:

我有一个 UITableView,它在每个单元格中显示一个 UILabel。每个项目的文本长度各不相同。

[@"Test1",@"Test 245", @Test 568974"]

现在我想确定可以正确适应最大文本的字体大小。在这种情况下,我需要找到 UILabel 的字体大小,它可以正确显示文本 @Test 568974" 而不会被截断。

我尝试过使用

调整FontSizeToFitWidth

属性和设置

自动调整字体

在故事板中以最小字体大小。但这使得每个文本都有不同的字体大小。

怎么做?

【问题讨论】:

    标签: ios objective-c uilabel uifont


    【解决方案1】:

    我终于找到了解决办法,

    -(CGFloat)findFontSizeforLabel:(UILabel*)label{
        CGFloat minFontSize = 22;
        for(Product *product in products){
            CGFloat fontSize = 22.0;
            while(fontSize > 0){
                NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"fontname" size:fontSize]};
                CGSize size = [product.title sizeWithAttributes:attributes];
                if(size.width < label.frame.size.width - 15){
                    if(fontSize < minFontSize){
                        minFontSize = fontSize;
                    }
                    break;
                }
                fontSize--;
            }
        }
        return minFontSize;
    }
    

    【讨论】:

      【解决方案2】:

      NSString 有一个方法sizeWithAttributes:

      创建具有所需文本属性的字典,例如:

      attrs = [NSDictionary dictionaryWithObject:yourFont forKey: NSFontAttributeName]
      

      并使用上面的方法获取边界矩形。请注意,您需要将返回的小数值舍入为整数值。

      这样可以在合理的字体大小之间进行二分搜索以适合您的最大标签。

      【讨论】:

        【解决方案3】:

        要使标签可调整大小添加到界面构建器约束,如下所示: 并为您的表格设置 rowHeight 为 Automatic 和estimatedRowheight 超过 45:

        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableViewAutomaticDimension
        

        这会使您的单元格调整标签高度。 如果您想以编程方式获取标签高度,请使用:

        NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
        CGRect rect = [textToMeasure boundingRectWithSize:label.frame.size
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributes
                                                  context:nil];
        

        这为您提供给定标签大小和属性的大小文本

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-02
          • 2010-09-14
          相关资源
          最近更新 更多