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

좋은 웹페이지 즐겨찾기