本文只作自用筆記,不喜勿噴,誠謝糾錯。
1.將字符串轉換成NSString
let messtr = "判斷字符串寬高" as NSString
let width = messtr.size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 18)]).width
let height = messtr.size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 18)]).height
print("寬:\(width)","高:\(height)")
打印結果:
寬:128.394 高:21.4805
2.純swift實現
let messtring:String = "判斷字符串寬高"
let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 18)] //設置字體大小
let option = NSStringDrawingOptions.usesLineFragmentOrigin
//這里有個參數1——width和參數2——heigh經測試應該是設置橫向和縱向的最大計算寬度和高度,如有不妥希望指出,相互學習,謝謝。(即當寬度接近與320.0時,就會換行,通過改變高度來計算字符串長度)
let rect:CGRect = messtring.boundingRect(with: CGSize.init(width: 320.0, height: 999.9), options: option, attributes: attributes, context: nil)//獲取字符串的frame
print("寬:\(rect.width),高:\(rect.height)")
打印結果:
寬:128.394,高:21.4805