
image.png
String扩展:
extension String {
func getStringSize(font: UIFont, viewSize: CGSize) -> CGSize {
let rect = self.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin,.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: font], context: nil)
return rect.size
}
}
一、固定高度,获取宽度
let str1 = "文本测试文本测试文本测试文本测试"
topLabel.text = str1
let labelw = str1.getStringSize(font: .systemFont(ofSize: 16), viewSize: CGSize(width: kscreenw-40, height: 40)).width+2*10 //左右间距为10
topLabel.frame = CGRect(x: 20, y: 100, width: labelw, height: 40)
二、固定高度,获取宽度
let str2 = "文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试文本测试"
botLabel.text = str2
let botLabH = str2.getStringSize(font: .systemFont(ofSize: 18), viewSize: CGSize(width: kscreenw-40, height: CGFloat(MAXFLOAT))).height
botLabel.frame = CGRect(x: 20, y: topLabel.frame.maxY+30, width: kscreenw-40, height:botLabH)