Replacement for deprecated sizeWithFont: in iOS 7?

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

    Building on @bitsand, this is a new method I just added to my NSString+Extras category:

    - (CGRect) boundingRectWithFont:(UIFont *) font constrainedToSize:(CGSize) constraintSize lineBreakMode:(NSLineBreakMode) lineBreakMode;
    {
        // set paragraph style
        NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        [style setLineBreakMode:lineBreakMode];
    
        // make dictionary of attributes with paragraph style
        NSDictionary *sizeAttributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName: style};
    
        CGRect frame = [self boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:sizeAttributes context:nil];
    
        /*
        // OLD
        CGSize stringSize = [self sizeWithFont:font
                                  constrainedToSize:constraintSize
                                      lineBreakMode:lineBreakMode];
        // OLD
        */
    
        return frame;
    }
    

    I just use the size of the resulting frame.

提交回复
热议问题