如何修复 'sizeWithFont:constrainedToSize:lineBreakMode:' 已弃用:警告

How to fix 'sizeWithFont:constrainedToSize:lineBreakMode:' is deprecated: warning

我的密码是

CGSize textSize =  [text sizeWithFont:font constrainedToSize:CGSizeMake(self.bounds.size.width - 106, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

有人知道我该如何解决这个警告吗?

Swift

 // adjust the label height (top align text)
// old
var labelSize: CGSize = model.name.sizeWithFont(self.nameLabel.font,  constrainedToSize: maxNameLabelSize, lineBreakMode: self.nameLabel.lineBreakMode)
// new
var labelSize: CGSize = model.name.boundingRectWithSize(maxNameLabelSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: self.nameLabel.font], context: nil).size

Objective c

 // adjust the label height (top align text)
 // old
CGSize labelSize = [model.name sizeWithFont:self.nameLabel.font
                      constrainedToSize:_maxNameLabelSize
                          lineBreakMode:self.nameLabel.lineBreakMode];
 // new
CGSize labelSize = [model.name boundingRectWithSize:_maxNameLabelSize
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName: self.nameLabel.font}
                                        context:nil].size;

试试下面的代码:

 NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:@"This is long text..!!!" attributes:@{NSFontAttributeName: self.lbl.font
 }];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){self.lbl.frame.size.width, CGFLOAT_MAX}
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];

NSLog(@"Height %f",rect.size.height);
NSLog(@"Width %f",rect.size.width);

使用这个:

CGRect textRect = [text boundingRectWithSize:CGSizeMake(self.bounds.size.width - 106, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:[[UIFont fontWithName:@"YOUR_FONT_NAME" size:12.0f]]}
                                 context:nil];

CGSize size = textRect.size;