不推荐使用'sizeWithFont:constrainedToSize:'替换

时间:2014-02-27 11:35:12

标签: objective-c ios7

有人知道如何使用-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;
});

2 个答案:

答案 0 :(得分:2)

目前你有......

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

答案 1 :(得分:0)

例如这样

-(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;
}