iOS获取带有换行符的内容的高度

常规不带换行符的方法

  // 获取Label的高度
    func getLabelHeight(labelTitle: String, font: CGFloat, width: CGFloat) -> CGFloat {
        
        let statusLabelText : NSString = labelTitle as NSString
        
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        
        let dic  = NSDictionary(object: UIFont.systemFont(ofSize: font), forKey: NSFontAttributeName as NSCopying)
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : Any], context: nil).size
        
        return strSize.height
        
    }
    
    // 获取Label的宽度
    func getLabelWidth(labelTitle: String, font: CGFloat, height: CGFloat) -> CGFloat {
        
        let statusLabelText : NSString = labelTitle as NSString
        
        let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
        
        let dic  = NSDictionary(object: UIFont.systemFont(ofSize: font), forKey: NSFontAttributeName as NSCopying)
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : Any], context: nil).size
        
        return strSize.width
        
    }

带有换行符等特殊符号的

 func heightForContent(str : String, width: CGFloat,font: CGFloat) -> CGFloat {
        
        let textView = UITextView(frame: CGRect(x: 0, y: 0, width: width, height: 10))
        
        textView.text = str
        
        textView.font = UIFont.systemFont(ofSize: font)
        
        let size = CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))
        let constraint = textView.sizeThatFits(size)
        return constraint.height
    }

总结

第二种好像是通用的,符合各种情况,大家可以测试一下。

你可能感兴趣的:(iOS获取带有换行符的内容的高度)