首页 > 编程语言 > 详细

Swift 字符串动态计算高度

时间:2021-05-29 09:10:13      阅读:17      评论:0      收藏:0      [点我收藏+]

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())

 

Swift 字符串动态计算高度

原文:https://www.cnblogs.com/akiha/p/14824293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!