常規(guī)不帶換行符的方法
// 獲取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
}
帶有換行符等特殊符號(hào)的
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
}
總結(jié)
第二種好像是通用的栓辜,符合各種情況恋拍,大家可以測(cè)試一下。