Swift 字符串动态计算高度


extension String {

    // 根据字符串的实际内容,在固定的宽度和字体的大小下,动态的计算出实际的高度
    func textHeightFromTextString(text: String, textWidth: CGFloat, fontSize: CGFloat, isBold: Bool) -> CGFloat {
        if (getCurrentIOS() >= 7.0) {
            var dict: NSDictionary = NSDictionary()
            if (isBold) {
                dict = NSDictionary(object: UIFont.boldSystemFont(ofSize: fontSize),forKey: NSAttributedString.Key.font as NSCopying)
            } else {
                dict = NSDictionary(object: UIFont.systemFont(ofSize: fontSize),forKey: NSAttributedString.Key.font as NSCopying)
            }
            
            let rect: CGRect = (text as NSString).boundingRect(with: CGSize(width: textWidth,height: CGFloat(MAXFLOAT)), options: [NSStringDrawingOptions.truncatesLastVisibleLine, NSStringDrawingOptions.usesFontLeading,NSStringDrawingOptions.usesLineFragmentOrigin],attributes: dict as? [NSAttributedString.Key : Any] ,context: nil)
            return rect.size.height
        } else {
            return 0.0
        }
    }
}

使用:

let titleStrHeight = "title".textHeightFromTextString(text: "title", textWidth: self.contentView.width - 32.auto(), fontSize: 16.auto(), isBold: false)

拓展:

动态获取UILabel高度或者宽度

extension UILabel {
    //根据宽度动态计算高度(old)
    func getLabelHeight(_ text: NSAttributedString, width: CGFloat) -> CGFloat {
        let contentHeight = text.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin], context: nil).height
        return contentHeight
    }
    
    // 根据宽度动态计算高度(new)
    func getLabelHeight(_ label: UILabel, width: CGFloat) -> CGFloat {
        return label.sizeThatFits(CGSize(width:width, height: CGFloat(MAXFLOAT))).height
    }
    
    //根据高度动态计算宽度(old)
    func getLabelWidth(_ text: NSAttributedString, height: CGFloat) -> CGFloat {
        let contentWidth = text.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: [.usesLineFragmentOrigin], context: nil).width
        return contentWidth
    }
    
    //根据高度动态计算宽度(new)
    func getLabelWidth(_ label: UILabel, height: CGFloat) -> CGFloat {
        return label.sizeThatFits(CGSize(width:CGFloat(MAXFLOAT), height: height)).width
    }
}

 使用:

let tiplblHeight = self.tipLabel.getLabelHeight(self.tipLabel, width: 128.5.auto())

 

posted @ 2021-05-29 02:28  仲长可倾  阅读(1600)  评论(0编辑  收藏  举报