已注解 (Annotated)

Version License Platform

已注解 (Annotated) 是一个小型库,允许你使用语义注解来注解你的字符串。一旦 String 被注解,你可以将其转换为 NSAttributedString 或 SwiftUI 的 Text

例如,它允许你在你的视图模型 (View Model) 中语义地注解一个 String,而无需考虑最终的视觉样式,然后可以在你的视图 (View) 中将你的 String 渲染为 NSAttributedString

要求

安装

已注解 (Annotated) 可通过 CocoaPods 和 SwiftPM 获取

示例

首先,你需要定义你的注解。使用 enum 通常是一个很好的选择。

enum AddressAnnotations: Hashable {
    case city, postalCode, highlighted
}

然后,你可以使用字符串字面量创建你的 Annotated<AddressAnnotations> 字符串。借助自定义字符串插值,你可以直接注解字符串的各个部分。

var string: Annotated<AddressAnnotations> = """
1 Infinite Loop
\("Cupertino", .city), CA \(95014, .postalCode)
"""

你也可以手动添加注解。

string.addAnnotation(.highlighted, at: 0..<1)
string.addAnnotation(.highlighted, forOccurencesOf: "in", options: .caseInsensitive)

最后,你可以使用提供的工厂方法将你的字符串渲染成 NSAttributedString 或 SwiftUI 的 Text

let attributedString = string.makeAttributedString { annotation in
  switch annotation {
  case nil:          return [.font: UIFont.systemFont(ofSize: 24)]
  case .city:        return [.font: UIFont.boldSystemFont(ofSize: 24)]
  case .postalCode:  return [.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)]
  case .highlighted: return [.foregroundColor: UIColor.systemRed]
  }
}
let text = string.makeText { annotation in
  switch annotation {
  case nil:          return { $0.font(.system(size: 24)) }
  case .city:        return { $0.bold() }
  case .postalCode:  return { $0.underline() }
  case .highlighted: return { $0.foregroundColor(.red) }
  }
}

作者

Jérôme Alves

许可证

已注解 (Annotated) 基于 MIT 许可证发布。请参阅 LICENSE 文件以获取更多信息。