在ios7中,sizeWithFont:现在已弃用。我现在如何在UIFont对象传递到替换方法sizeWithAttributes:?


当前回答

改用sizeWithAttributes:,它现在接受一个NSDictionary。传入key UITextAttributeFont和你的字体对象,如下所示:

CGRect rawRect = {};
rawRect.size = [string sizeWithAttributes: @{
    NSFontAttributeName: [UIFont systemFontOfSize:17.0f],
}];

// Values are fractional -- you should take the ceil to get equivalent values
CGSize adjustedSize = CGRectIntegral(rawRect).size;

其他回答

正如你在苹果开发者网站上看到的sizeWithFont,它已被弃用,所以我们需要使用sizeWithAttributes。

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

NSString *text = @"Hello iOS 7.0";
if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
    // code here for iOS 5.0,6.0 and so on
    CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" 
                                                         size:12]];
} else {
    // code here for iOS 7.0
   CGSize fontSize = [text sizeWithAttributes: 
                            @{NSFontAttributeName: 
                              [UIFont fontWithName:@"Helvetica" size:12]}];
}
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
float heightUse = expectedLabelSize.height;

正如@Ayush的回答:

正如你在苹果开发者网站上看到的sizeWithFont,它已被弃用,所以我们需要使用sizeWithAttributes。

好吧,假设在2019+你可能会使用Swift和String而不是Objective-c和NSString,下面是使用预定义字体获取字符串大小的正确方法:

let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])
- (CGSize) sizeWithMyFont:(UIFont *)fontToUse
{
    if ([self respondsToSelector:@selector(sizeWithAttributes:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:fontToUse};
        return ([self sizeWithAttributes:attribs]);
    }
    return ([self sizeWithFont:fontToUse]);
}

试试这个语法:

NSAttributedString *attributedText =
    [[NSAttributedString alloc] initWithString:text 
                                    attributes:@{NSFontAttributeName: font}];