警告

此仓库已被存档。

从 macOS 12+ / iOS 15+ / tvOS 15+ / watchOS 8+ 开始,您可以使用带有 SwiftUI Text 视图的 AttributedString

AttributedText

Twitter: @gonzalezreal

AttributedText 是一个 Swift 微型包,它通过包装 NSTextViewUITextView(具体取决于平台)来提供在 SwiftUI 中渲染 NSAttributedString 的功能。

支持的平台

用法

import AttributedText
import SwiftUI

struct ContentView: View {
  var body: some View {
    AttributedText {
      let result = NSMutableAttributedString(
        string: """
          After the Big Bang
          A brief summary of time
          Life on earth
          10 billion years
          You reading this
          13.7 billion years
          """
      )

      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .title1)],
        range: NSRange(location: 0, length: 18)
      )
      result.addAttributes(
        [.link: URL(string: "https://en.wikipedia.org/wiki/Big_Bang")!],
        range: NSRange(location: 10, length: 8)
      )
      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .body)],
        range: NSRange(location: 19, length: 23)
      )
      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .title2)],
        range: NSRange(location: 43, length: 13)
      )
      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .body)],
        range: NSRange(location: 57, length: 16)
      )
      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .title2)],
        range: NSRange(location: 74, length: 16))
      result.addAttributes(
        [.font: UIFont.preferredFont(forTextStyle: .body)],
        range: NSRange(location: 91, length: 18)
      )

      return result
    }
    .background(Color.gray.opacity(0.5))
    .accentColor(.purple)
  }
}

iOSScreenshot

AttributedText 视图会占用所有可用宽度,并调整其高度以适应内容。

要更改文本对齐方式或换行模式,您需要向属性字符串添加一个 .paragraphStyle 属性。

安装

您可以通过将其作为包依赖项添加到 Xcode 项目中,来添加 AttributedText。

  1. 文件 菜单中,选择 Swift Packages › Add Package Dependency… (Swift 包 › 添加包依赖项…)
  2. 在包存储库 URL 文本字段中输入 https://github.com/gonzalezreal/AttributedText
  3. AttributedText 链接到您的应用程序目标