Swift之测量NSAttributedString文字尺寸
在使用 NSAttributedString 设置 UILabel 的文本时,计算文本尺寸的方法与使用 NSString 时略有不同。你可以使用 boundingRect(with:options:context:) 方法,但需要注意的是,应该在 NSAttributedString 上使用 size() 方法来获取其尺寸。
以下是一个示例,展示如何计算使用 NSAttributedString 设置的字符串的尺寸:
import UIKit
// 创建一个 NSAttributedString
let attributedString = NSAttributedString(string: "Hello, world!", attributes: [
.font: UIFont.systemFont(ofSize: 17),
.foregroundColor: UIColor.black
])
// 设置计算区域的宽度和高度
let maxSize = CGSize(width: 200, height: .greatestFiniteMagnitude)
// 计算尺寸
let boundingRect = attributedString.boundingRect(with: maxSize, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
// 结果是 boundingRect.size
print("Height: \(boundingRect.height), Width: \(boundingRect.width)")
说明:
NSAttributedString:创建一个具有特定属性的字符串。maxSize:设置你希望计算的最大尺寸。在这里,宽度设置为 200,高度可以设置为.greatestFiniteMagnitude,表示没有限制。boundingRect(with:options:context:):对NSAttributedString调用这个方法,计算出所需的尺寸。- 选项:
usesLineFragmentOrigin和usesFontLeading是常用的选项,可以确保正确计算多行文本的大小。
其他注意事项:
- 如果你的文本在多行中显示,确保将
UILabel的numberOfLines属性设置为0,以便可以自适应文本的高度。 - 根据
UILabel的布局需求,可能需要进一步考虑边距和其他因素来调整计算尺寸。
通过这种方法,你可以准确地计算出 NSAttributedString 的尺寸,以便在设置 UILabel 的框架时使用。

浙公网安备 33010602011771号