NSString sizeWithFont: alternative in iOS7

前端 未结 2 842
一生所求
一生所求 2021-01-13 22:59

The method (sizeWithFont: forWidth: lineBreakMode:) was deprecated in iOS 7.0.

But how can I do a same thing like following code in iOS 7.0?

相关标签:
2条回答
  • 2021-01-13 23:44

    For those who want the height with width function but in swift its:

    func HeigthWithWidth(stringToSize : String, width : CGFloat, font : UIFont) -> CGFloat {
        var attrStr = NSMutableAttributedString(string: stringToSize);
        attrStr.addAttribute(NSFontAttributeName, value: font, range: NSRange.init(location: 0, length: stringToSize.characters.count));
        var rect = attrStr.boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], context: nil);
        return rect.size.height;
    }
    

    Hope that helps those who come looking later

    0 讨论(0)
  • 2021-01-13 23:46

    I have got a category for NSString to get the width or heigth of a string:

    - (CGFloat)widthWithFont:(UIFont *)font
    {
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
        return [[[NSAttributedString alloc] initWithString:self attributes:attributes] size].width;
    }
    
    - (CGFloat)heigthWithWidth:(CGFloat)width andFont:(UIFont *)font
    {
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self];
        [attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [self length])];
        CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
        return rect.size.height;
    }
    
    0 讨论(0)
提交回复
热议问题