Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

swift - SwiftUI: is there exist modifier to highlight substring of Text() view?

I have some text on the screen:

Text("someText1")

is it possible to highlight/select part of the text without creating lot Text items

I mean

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

is not solution for me

Better to have some sort of modifier to highlight by some way part of the text. Something similar to:

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

Is it possible? (without creation of lot of views I mean)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once you create a Text, you cannot open it back up. Your example creates localization problems. someText1 is not actually the string to print. It's the localization key of the string. The default localized string just happens to be the key, so it works. Your attempt to search for eTex would quietly break when you localize. So this wouldn't be a good general-purpose interface.

Even so, building a solution is very enlightening, and may be useful for specific cases.

The fundamental goal is to think of styles as attributes that are applied to ranges. That's exactly what NSAttributedString gives us, including the ability to merge and split ranges in order to manage multiple, overlapping attributes. NSAttributedString is not particularly Swift-friendly, so there could be some value in reimplementing it from scratch, but instead, I'm just going to hide it as an implementation detail.

So a TextStyle is going to be an NSAttributedString.Key and a function that translates a Text into another Text.

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 is opaque. To construct it, we expose some extensions, for example:

// 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() })
    }
}

It's noteworthy here that NSAttributedString is just "an string annotated by attributes over ranges." It's not "a styled string." We can make up any attribute keys and values we want. So these are intentionally not the same attributes that Cocoa uses for formatting.

Next, we create the StyledText itself. I'm focusing first on the "model" part of this type (later we'll make it a View).

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)
    }
}

It's just a wrapper around an NSAttributedString and a way to create new StyledTexts by applying TextStyles to ranges. Some important points:

  • Calling style does not mutate the existing object. If it did, you couldn't do things like return StyledText("text").apply(.bold()). You'd get an error that the value is immutable.

  • Ranges are tricky things. NSAttributedString uses NSRange, and has a different concept of index than String. NSAttributedStrings can be a different length than the underlying String because they compose characters differently.

  • You can't safely take a String.Index from one String and apply it to another String, even if the two Strings seem identical. That's why this system takes a closure for creating ranges rather than taking a range itself. attributedString.string is not exactly the same string as the one that was passed in. If the caller wanted to pass Range<String.Index>, it would be critical that they construct it with precisely the same string that TextStyle uses. This is easiest to ensure by using a closure and avoids a lot of corner cases.

The default style interface handles a sequence of ranges for flexibility. But in most cases you'll probably pass just one range, so it's nice to have a convenience method for that, and for the case where you want the whole string:

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)] })
    }
}

Now, the public interface for creating a 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)
    }
}

Note the verbatim here. This StyledText doesn't support localization. It's conceivable that with work it could, but a lot more thought would have to go into that.

And finally, after all that, we can make it a View, by creating a Text for each substring that has the same attributes, applying all the styles to that Text, and then combining all the Texts into one using +. For convenience, the Text is directly exposed so you can combine it with standard views.

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
    }
}

And that's it. Using it looks like this:

// 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())
    }
}

Image of text with red highlighting and bold

Gist

You could also just wrap a UILabel in a UIViewRepresentable, and use attributedText. But that would be cheating. :D


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...