IOS 7 sizeWithFont Deprecated

余生长醉 提交于 2019-11-28 09:19:26

问题


I cannot seem to replace the deprecated sizeWithFont with boundingRecWithSize correctly. I scoured through all the answers and stayed up all night trying to fix this.I really need help from someone way smarter than I. Here is the code I am trying to modify. Any help would be appreciated.

CGSize sizeForText = [faqItem.answer sizeWithFont:[UIFont boldSystemFontOfSize:14]
   constrainedToSize:CGSizeMake(self.tblView.bounds.size.width - padding, MAXFLOAT)
   lineBreakMode:NSLineBreakByWordWrapping];

[sectionInfo insertObject:[NSNumber numberWithFloat:roundf(sizeForText.height + 5)]
  inRowHeightsAtIndex:0];

回答1:


In apple documentation:

sizeWithFont: Returns the size of the string if it were to be rendered with the specified font on a single line. (Deprecated in iOS 7.0. Use sizeWithAttributes: instead.)

  • (CGSize)sizeWithFont:(UIFont *)font Parameters font The font to use for computing the string size. Return Value The width and height of the resulting string’s bounding box. These values may be rounded up to the nearest whole number.

So you can use sizeWithAttributes: like this:

 CGSize sizeForText = [faqItem.answer sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]}
                       constrainedToSize:CGSizeMake(self.tblView.bounds.size.width - padding, MAXFLOAT) 
                           lineBreakMode:NSLineBreakByWordWrapping];

[sectionInfo insertObject:[NSNumber numberWithFloat:roundf(sizeForText.height + 5)] 
      inRowHeightsAtIndex:0];



回答2:


You need to use the sizeWithAttributes property.

CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]}];

You can also set it to an already created font size in order to reduce recoding if you use the size more than once:

CGSize mysize = [string sizeWithAttributes:@{NSFontAttributeName: label1.font}];

I do not believe you can use constrainedToSize with this property. It would have to be separately set on a CGRect.




回答3:


I wrote an sample for you, hope it's helpful.

NSString *text = @"    // Do any additional setup after loading the view, typically from a nib.";
CGRect rect = CGRectZero;
NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};

rect = [text boundingRectWithSize:CGSizeMake(100,9999)
                          options:(NSStringDrawingUsesLineFragmentOrigin)
                       attributes:attrDict
                          context:Nil];

UILabel *lbl = [[UILabel alloc] init];
lbl.text = text;
rect.origin = CGPointMake(50, 200);
lbl.frame = rect;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
[self.view addSubview:lbl];
lbl.backgroundColor = [UIColor lightGrayColor];


来源:https://stackoverflow.com/questions/19591621/ios-7-sizewithfont-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!