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

时间:2016-04-27 13:02:46

标签: ios objective-c deprecation-warning

我的代码是

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

任何人都知道如何修复此警告?

3 个答案:

答案 0 :(得分:11)

  

夫特

 // 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
  

目标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;

答案 1 :(得分:1)

尝试以下代码:

 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);

答案 2 :(得分:0)

使用此:

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;