Replacement for deprecated sizeWithFont: in iOS 7?

后端 未结 20 1375
难免孤独
难免孤独 2020-11-22 08:49

In iOS 7, sizeWithFont: is now deprecated. How do I now pass in the UIFont object into the replacement method sizeWithAttributes:?

20条回答
  •  借酒劲吻你
    2020-11-22 08:51

    In iOS7 I needed the logic to return the correct height for the tableview:heightForRowAtIndexPath method, but the sizeWithAttributes always returns the same height regardless of the string length because it doesn't know that it is going to be put in a fixed width table cell. I found this works great for me and calculates the correct height taking in consideration the width for the table cell! This is based on Mr. T's answer above.

    NSString *text = @"The text that I want to wrap in a table cell."
    
    CGFloat width = tableView.frame.size.width - 15 - 30 - 15;  //tableView width - left border width - accessory indicator - right border width
    UIFont *font = [UIFont systemFontOfSize:17];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    size.height = ceilf(size.height);
    size.width  = ceilf(size.width);
    return size.height + 15;  //Add a little more padding for big thumbs and the detailText label
    

提交回复
热议问题