iOS获取字符串在Label上显示的bounds

cell自适应高度时需要计算label上显示字符串后的大小,根据字符串的方法boundingRectWithSize实现。
OC代码:扩展NSString

- (CGRect)boundsWithConstrainedWidth:(CGFloat)width WithFont:(UIFont *)font {
    NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:16] };
    CGRect rect = [self boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 55, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributes context:nil];
    return rect;
}

- (CGFloat)widthWithConstrainedWidth:(CGFloat)width WithFont:(UIFont *)font {
    return [self boundsWithConstrainedWidth:width WithFont:font].size.width;
}

- (CGFloat)heightWithConstrainedWidth:(CGFloat)width WithFont:(UIFont *)font {
    return [self boundsWithConstrainedWidth:width WithFont:font].size.height;
}

Swift代码:扩展String

extension String {
    func boundsWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGRect {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let bounds = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return bounds
    }
    func widthWithConstrainedWidth(width: CGFloat, font: UIFont) -> Float {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let bounds = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return bounds.width
    }
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let bounds = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return bounds.height
    }
}

你可能感兴趣的:(代码,自适应高度,iOS,swift)