Replacement for deprecated sizeWithFont: in iOS 7?

后端 未结 20 1458
难免孤独
难免孤独 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 09:09

    Multi-line labels using dynamic height may require additional information to set the size properly. You can use sizeWithAttributes with UIFont and NSParagraphStyle to specify both the font and the line-break mode.

    You would define the Paragraph Style and use an NSDictionary like this:

    // set paragraph style
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [style setLineBreakMode:NSLineBreakByWordWrapping];
    // make dictionary of attributes with paragraph style
    NSDictionary *sizeAttributes        = @{NSFontAttributeName:myLabel.font, NSParagraphStyleAttributeName: style};
    // get the CGSize
    CGSize adjustedSize = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    
    // alternatively you can also get a CGRect to determine height
    CGRect rect = [myLabel.text boundingRectWithSize:adjustedSize
                                                             options:NSStringDrawingUsesLineFragmentOrigin
                                                          attributes:sizeAttributes
                                                             context:nil];
    

    You can use the CGSize 'adjustedSize' or CGRect as rect.size.height property if you're looking for the height.

    More info on NSParagraphStyle here: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSParagraphStyle_Class/Reference/Reference.html

提交回复
热议问题