美文网首页iOS开发交流专辑iOS开发知识小集
iOS获取带有换行符的内容的高度

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

作者: 伪文艺的程序员 | 来源:发表于2018-07-17 17:35 被阅读8次

    常规不带换行符的方法

      // 获取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获取带有换行符的内容的高度

        本文链接:https://www.haomeiwen.com/subject/oyegpftx.html