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)")

说明:

  1. NSAttributedString:创建一个具有特定属性的字符串。
  2. maxSize:设置你希望计算的最大尺寸。在这里,宽度设置为 200,高度可以设置为 .greatestFiniteMagnitude,表示没有限制。
  3. boundingRect(with:options:context:):对 NSAttributedString 调用这个方法,计算出所需的尺寸。
  4. 选项usesLineFragmentOriginusesFontLeading 是常用的选项,可以确保正确计算多行文本的大小。

其他注意事项:

  • 如果你的文本在多行中显示,确保将 UILabelnumberOfLines 属性设置为 0,以便可以自适应文本的高度。
  • 根据 UILabel 的布局需求,可能需要进一步考虑边距和其他因素来调整计算尺寸。

通过这种方法,你可以准确地计算出 NSAttributedString 的尺寸,以便在设置 UILabel 的框架时使用。

posted @   looxy  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示