首页 > 解决方案 > SwiftUI:是否存在修饰符来突出显示 Text() 视图的子字符串?

问题描述

我在屏幕上有一些文字:

Text("someText1")

是否可以在不创建大量文本项目的情况下突出显示/选择部分文本

我是说

Text("som") + Text("eTex").foregroundColor(.red) + Text("t1")

不是我的解决方案

最好有某种修饰符以某种方式突出显示文本的一部分。类似于:

Text("someText1").modifier(.highlight(text:"eTex"))

可能吗?(我的意思是没有创建很多视图)

标签: swiftswiftui

解决方案


创建文本后,您将无法重新打开它。您的示例会产生本地化问题。someText1实际上不是要打印的字符串。它是字符串的本地化键。默认的本地化字符串恰好是键,所以它可以工作。当您进行本地化时,您的搜索尝试eTex会悄然中断。所以这不是一个好的通用接口。

即便如此,构建解决方案非常有启发性,并且可能对特定情况有用。

基本目标是将样式视为应用于范围的属性。这正是 NSAttributedString 为我们提供的,包括合并和拆分范围以管理多个重叠属性的能力。NSAttributedString 对 Swift 不是特别友好,因此从头开始重新实现它可能会有一些价值,但是,我只是将它作为实现细节隐藏起来。

所以 TextStyle 将是一个 NSAttributedString.Key 和一个将文本转换为另一个文本的函数。

public struct TextStyle {
    // This type is opaque because it exposes NSAttributedString details and
    // requires unique keys. It can be extended by public static methods.

    // Properties are internal to be accessed by StyledText
    internal let key: NSAttributedString.Key
    internal let apply: (Text) -> Text

    private init(key: NSAttributedString.Key, apply: @escaping (Text) -> Text) {
        self.key = key
        self.apply = apply
    }
}

TextStyle 是不透明的。为了构建它,我们公开了一些扩展,例如:

// Public methods for building styles
public extension TextStyle {
    static func foregroundColor(_ color: Color) -> TextStyle {
        TextStyle(key: .init("TextStyleForegroundColor"), apply: { $0.foregroundColor(color) })
    }

    static func bold() -> TextStyle {
        TextStyle(key: .init("TextStyleBold"), apply: { $0.bold() })
    }
}

这里值得注意的是 NSAttributedString 只是“一个由范围内的属性注释的字符串”。它不是“样式化的字符串”。我们可以组成任何我们想要的属性键和值。因此,这些属性故意与 Cocoa 用于格式化的属性不同。

接下来,我们创建 StyledText 本身。我首先关注这种类型的“模型”部分(稍后我们将使其成为视图)。

public struct StyledText {
    // This is a value type. Don't be tempted to use NSMutableAttributedString here unless
    // you also implement copy-on-write.
    private var attributedString: NSAttributedString

    private init(attributedString: NSAttributedString) {
        self.attributedString = attributedString
    }

    public func style<S>(_ style: TextStyle,
                         ranges: (String) -> S) -> StyledText
        where S: Sequence, S.Element == Range<String.Index>?
    {

        // Remember this is a value type. If you want to avoid this copy,
        // then you need to implement copy-on-write.
        let newAttributedString = NSMutableAttributedString(attributedString: attributedString)

        for range in ranges(attributedString.string).compactMap({ $0 }) {
            let nsRange = NSRange(range, in: attributedString.string)
            newAttributedString.addAttribute(style.key, value: style, range: nsRange)
        }

        return StyledText(attributedString: newAttributedString)
    }
}

它只是一个 NSAttributedString 的包装器,也是一种通过将 TextStyles 应用于范围来创建新 StyledTexts 的方法。一些重要的点:

  • 调用style不会改变现有对象。如果是这样,您将无法执行类似return StyledText("text").apply(.bold()). 您会收到一个错误,即该值是不可变的。

  • 范围是棘手的事情。NSAttributedString 使用 NSRange,并且具有与 String 不同的索引概念。NSAttributedStrings 的长度可以与底层字符串不同,因为它们组成字符的方式不同。

  • String.Index即使两个字符串看起来相同,您也不能安全地从一个字符串中获取一个并将其应用于另一个字符串。这就是为什么该系统采用闭包来创建范围而不是采用范围本身。attributedString.string与传入的字符串不完全相同。如果调用者想要传递Range<String.Index>,那么他们使用与 TextStyle 使用的完全相同的字符串来构造它是至关重要的。这是通过使用闭包最容易确保的,并且避免了很多极端情况。

默认style接口处理一系列范围以实现灵活性。但在大多数情况下,您可能只会通过一个范围,因此最好有一个方便的方法,并且对于您想要整个字符串的情况:

public extension StyledText {
    // A convenience extension to apply to a single range.
    func style(_ style: TextStyle,
               range: (String) -> Range<String.Index> = { $0.startIndex..<$0.endIndex }) -> StyledText {
        self.style(style, ranges: { [range($0)] })
    }
}

现在,创建 StyledText 的公共接口:

extension StyledText {
    public init(verbatim content: String, styles: [TextStyle] = []) {
        let attributes = styles.reduce(into: [:]) { result, style in
            result[style.key] = style
        }
        attributedString = NSMutableAttributedString(string: content, attributes: attributes)
    }
}

注意verbatim这里。此 StyledText 不支持本地化。可以想象,通过工作可以做到这一点,但需要更多的思考。

最后,在这一切之后,我们可以通过为每个具有相同属性的子字符串创建一个 Text,将所有样式应用于该 Text,然后使用+. 为方便起见,文本直接公开,因此您可以将其与标准视图结合使用。

extension StyledText: View {
    public var body: some View { text() }

    public func text() -> Text {
        var text: Text = Text(verbatim: "")
        attributedString
            .enumerateAttributes(in: NSRange(location: 0, length: attributedString.length),
                                 options: [])
            { (attributes, range, _) in
                let string = attributedString.attributedSubstring(from: range).string
                let modifiers = attributes.values.map { $0 as! TextStyle }
                text = text + modifiers.reduce(Text(verbatim: string)) { segment, style in
                    style.apply(segment)
                }
        }
        return text
    }
}

就是这样。使用它看起来像这样:

// An internal convenience extension that could be defined outside this pacakge.
// This wouldn't be a general-purpose way to highlight, but shows how a caller could create
// their own extensions
extension TextStyle {
    static func highlight() -> TextStyle { .foregroundColor(.red) }
}

struct ContentView: View {
    var body: some View {
        StyledText(verbatim: "‍‍someText1")
            .style(.highlight(), ranges: { [$0.range(of: "eTex"), $0.range(of: "1")] })
            .style(.bold())
    }
}

带有红色突出显示和粗体的文本图像

要旨

您也可以将 UILabel 包装在 UIViewRepresentable 中,然后使用attributedText. 但这就是作弊。:D


推荐阅读