富文本视图 (AttributedText)

富文本视图 (AttributedText) 是一个用于使用 SwiftUI Text View 显示带有 HTML 标签文本的视图。

一个简单的使用示例。

代码示例

AttributedText("A unit of <i>length</i> equal to <b>one hundred-millionth of a centimetre</b>, 10<sup>−10</sup> metre, used mainly to express <u>wavelengths and interatomic distances</u>.")

结果

Example

特性

您可以克隆此仓库并运行 AttributedTextExample 项目来探索 AttributedText 的特性。

以下是需要注意的几个要点。

  1. 您可以定义需要的标签,或者使用默认标签。

    您需要设置所需的标签并提供关联的闭包。 每个闭包必须是一个修饰符,当遇到特定标签时,该修饰符会应用于 SwiftUI Text View

    覆盖默认值,例如在应用程序启动时。
    @main
    struct ExampleApp: App {
        init() {
            AttributedText.tags = [
                "b": { $0.bold() },
                "i": { $0.italic() }
            ]
        }
    }

    在这种情况下,只会处理 <b><i> 标签。 所有其他标签将被忽略或删除。

    为每个实例设置自定义值。
    private let tags: Dictionary<String, (Text) -> (Text)> = [
        // Set the necessary values.
    ]
    
    var body: some View {
        AttributedText("Text", tags: tags)
    }
  2. 仍然可以应用基本的修饰符,例如更改文本的字体和颜色。

    代码示例

    AttributedText("This is <b>bold</b> and <i>italic</i> text.")
        .foregroundColor(.blue)
        .font(.title)

    结果

    1 feature

  3. 处理未打开/未关闭的标签。

    代码示例

    AttributedText("This is italic</i> and <b>bold text.")

    结果

    2 feature

  4. 支持重叠标签。

    代码示例

    AttributedText("This is <b>bold only, <i>bold and italic</b> and italic only</i> text.")

    结果

    3 feature

  5. 删除没有修饰符的标签。

    代码示例

    AttributedText("<unknown>This is <b>bold</b> and <i>italic</i> text.</unknown>")

    结果

    4 feature

  6. 处理 HTML 字符,例如 &amp;

    代码示例

    AttributedText("This is <b>bold</b> &amp; <i>italic</i> text.")

    结果

    5 feature

  7. 仅支持单字标签。 包含多个单词或包含除字母数字以外的任何字符的标签将被忽略且不会被删除。

    代码示例

    AttributedText("This is <tag attribute1=\"value1\"> <b>bold</b> and <i>italic</i> text</tag>.")

    结果

    6 feature

安装和使用

通过 Swift Package Manager

  1. 在 Xcode 11 或更高版本中,选择 File ▸ Swift Packages ▸ Add Package Dependency
  2. 粘贴此仓库的链接 https://github.com/Iaenhaall/AttributedText.git 并点击 Next
  3. 为此软件包定义软件包选项或选择默认选项。 点击 Next
  4. Xcode 从 GitHub 下载代码并将软件包添加到您的项目目标。 点击 Finish

手动

  1. AttributedText.swiftHTML2TextParser.swift 文件添加到您的项目。