Swift获取字符串的宽高

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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容