SuperAPI AI 工具集

attributed-string

通用与其它

查看项目

更新于 10-16 01:13

技能介绍

用途:这是一套 Foundation AttributedString 的 API 模式与正确用法参考,帮助在 Swift 中创建和操作富文本,处理样式、排版、选择编辑以及 SwiftUI 集成。

主要能力:

  • 创建与样式:用 AttributedString 初始化文本,设置 font、foregroundColor、backgroundColor 等;对 range(of:) 返回的范围下标应用下划线等属性。
  • 段落排版:对齐(旧方式用 NSMutableParagraphStyle,iOS 26+ 可用 alignment = .center)、书写方向(writingDirection,.leftToRight/.rightToLeft)、行高(lineHeight,.exact(points:)、.multiple(factor:)、.loose)。
  • 文本选择与编辑(iOS 26+):AttributedTextSelection 配合 replaceSelection(&selection, withCharacters:) 或 replaceSelection(&selection, with:) 替换选中文本。
  • 非连续子串:用 RangeSet 与 DiscontiguousAttributedSubstring 处理多段不连续范围。
  • SwiftUI:TextEditor(text:selection:) 支持 AttributedString 富文本编辑;.textSelectionAffinity(_:) 控制行边界光标;Text 配合 .textSelection(.enabled) 显示可选文本。

必要用法与注意:AttributedString 是值类型,应用属性前需声明为 var;范围查找必须用 if let / guard let 安全解包,不要强解包;replaceSelection 的 selection 需以 inout 传入(&selection)。新 API 多要求 iOS 26 / macOS 26,旧目标需用旧段落样式并用 if #available 兼容。

适用场景:Swift 富文本排版、RTL、多行行高、文本选择编辑、SwiftUI 富文本编辑等。限制:具体性能与平台支持以官方文档为准,部分 API 版本门槛较高。