簡體   English   中英

不推薦使用'sizeWithFont:constrainedToSize:'替換

[英]deprecated ’sizeWithFont:constrainedToSize:' replacement

有人知道如何使用-boundingRectWithSize:options:attributes:context:在這種情況下替換不推薦使用的“sizeWithFont:constrainedToSize:”方法。

CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];

獲取警告:'sizeWithFont:constrainedToSize:'不推薦使用:首先在iOS 7.0中棄用 - 使用-boundingRectWithSize:options:attributes:context:

這是孔碼片:

 // calculate the label size

CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];

each_object(self.labels, ^(UILabel *label) {
    CGRect frame = label.frame;
    frame.origin.x = offset;
    frame.size.height = CGRectGetHeight(self.bounds);
    frame.size.width = labelSize.width + 2.f /*Magic number*/;
    label.frame = frame;


    // Recenter label vertically within the scroll view
    label.center = CGPointMake(label.center.x, roundf(self.center.y - CGRectGetMinY(self.frame)));

    offset += CGRectGetWidth(label.bounds) + self.labelSpacing;
});

目前你有......

CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];

所以用......

CGRect boundingRect = [self.mainLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                        context:nil];

CGSize labelSize = boundingRect.size;

這應該工作。

或者......有屬性......

CGRect boundingRect = [self.mainLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))
                                                        options:NSStringDrawingUsesLineFragmentOrigin 
                                                     attributes:@{NSFontAttributeName:self.mainLabel.font} 
                                                        context:nil];

例如這種方式

-(CGFloat)getLabelSize:(UILabel *)label fontSize:(NSInteger)fontSize
{


   NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont systemFontOfSize:fontSize], NSFontAttributeName,
                                      nil];

   CGRect frame = [label.text boundingRectWithSize:CGSizeMake(270, 2000.0)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:attributesDictionary
                                        context:nil];

   CGSize size = frame.size;

   return size.height;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM