【问题标题】:sizeWithFont: in iOS 7sizeWithFont:在 iOS 7 中
【发布时间】:2013-09-27 07:30:37
【问题描述】:

我收到警告:“'sizeWithFont:constrainedToSize:lineBreakMode:' 已弃用:iOS 7.0 中首次弃用” 任何人都可以建议我使用这种方法的替代方法吗?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Calculate height based on cell content — cell content will stretch appropriately when the height is set
Post *post = self.articleComments[indexPath.row];
CGFloat width = tableView.frame.size.width - 71 - 15;  // Width of comment text area
UIFont *commentFont = [UIFont fontWithName:@"SeroCompPro-Light" size:14];
CGFloat commentTextHeight = [post.text sizeWithFont:commentFont constrainedToSize:CGSizeMake(width, 10000) lineBreakMode:NSLineBreakByWordWrapping].height;

return commentTextHeight + 31 + 37;
}  

【问题讨论】:

标签: ios objective-c ios7


【解决方案1】:

替代方案是:

- (NSSize)sizeWithAttributes:(NSDictionary *)attributes

在你的情况下:

[string sizeWithAttributes:@{NSFontAttributeName:[UIFont fontwithName:@"SeroCompPro-Light" size:14]}];

【讨论】:

    【解决方案2】:

    此功能在 ios 7 中已弃用。 而不是这个函数

    sizeWithFont:constrainedToSize:lineBreakMode

    使用这个功能,使用

    - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context
    
     boundingRectWithSize:options:attributes:context:
    

    计算并返回使用给定选项和显示特性绘制的接收器的边界矩形,在当前图形上下文中的指定矩形内。

    参数 尺寸 要绘制的矩形的大小。

    选项 字符串绘制选项。

    属性 要应用于字符串的文本属性字典。这些是可以应用于NSAttributedString 对象的相同属性,但在NSString 对象的情况下,这些属性应用于整个字符串,而不是字符串中的范围。 上下文

    用于接收器的字符串绘制上下文,指定最小比例因子和跟踪调整。

    【讨论】:

    • 该功能从iOS 7开始可用,所以要注意向后兼容性。
    【解决方案3】:

    我使用了下面的代码,它可以工作:

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@
         {
         NSFontAttributeName: font
         }];
    
        CGRect rect = [attributedText boundingRectWithSize:(CGSize){size.width, CGFLOAT_MAX}
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
    
        result = CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));
    

    使用 ceilf 方法创建 NSAttributedString 并获得正确的宽度高度时出现问题

    【讨论】:

      【解决方案4】:

      支持IOS7及更低版本的替代方案-

      CGSize expectedLabelSize;
      if ([self respondsToSelector:@selector(sizeWithAttributes:)])
      {
          expectedLabelSize = [subTitle sizeWithAttributes:@{NSFontAttributeName:subTitleLabel.font}];
      }else{
          expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多