zoukankan      html  css  js  c++  java
  • 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( 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,  CGFloat) -> CGFloat {
            let contentHeight = text.boundingRect(with: CGSize( width, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin], context: nil).height
            return contentHeight
        }
        
        // 根据宽度动态计算高度(new)
        func getLabelHeight(_ label: UILabel,  CGFloat) -> CGFloat {
            return label.sizeThatFits(CGSize(width, height: CGFloat(MAXFLOAT))).height
        }
        
        //根据高度动态计算宽度(old)
        func getLabelWidth(_ text: NSAttributedString, height: CGFloat) -> CGFloat {
            let contentWidth = text.boundingRect(with: CGSize( CGFloat(MAXFLOAT), height: height), options: [.usesLineFragmentOrigin], context: nil).width
            return contentWidth
        }
        
        //根据高度动态计算宽度(new)
        func getLabelWidth(_ label: UILabel, height: CGFloat) -> CGFloat {
            return label.sizeThatFits(CGSize(CGFloat(MAXFLOAT), height: height)).width
        }
    }

     使用:

    let tiplblHeight = self.tipLabel.getLabelHeight(self.tipLabel,  128.5.auto())
  • 相关阅读:
    vim 插件之NERD tree
    vim 插件之supertab
    离开页面时发送请求
    修改属性item1(1变化)
    node+express 中安装nodemon实时更新server.js
    vue封装element中table组件
    mysql常用语句
    mysql新建表
    node+express POST请求
    node+express 发送get请求
  • 原文地址:https://www.cnblogs.com/akiha/p/14824293.html
Copyright © 2011-2022 走看看