1

I have a HighlightedText View which is initialized with a string, a default font and a highlight font. The string can have markers to indicate which portions of it need to be highlighted. That all works fine. Now, instead of initialize it with a default font and a highlight font, I would like to be able to write this in a more swift-ui way to allow for more flexibility and improve readiness. So I would like to be able to do something like this:

HighlightedText("My text <highlighted>")
   .defaultFont(.body)
   .highlightFont(.title)

I know the standard way should be using a ViewModifier, however all I get from within its body function is a Content type and there doesn't seem to be a way I could cast it into my HighlightedText view and configure it as needed. All I seem to be able to do from within its body is just call other modifiers from View protocol, but that's not enough for my use case.

I've tried this extension, where defaultFont is a file private @State property defined in HighlightedText:

extension HighlightedText {
    func defaultFont(_ font: Font) -> some View {
        defaultFont.font = font
        return body
    }
}

That however, does not work. The default font I pass over never gets applied.

mdonati
  • 1,049
  • 11
  • 24

1 Answers1

2

Here is possible solution:

if to you have declaration like

struct HighlightedText: View {
    var defaultFount = Font.body
    var highlightedFont = Font.headline

    // ... other code

then your custom modifiers could be as

extension HighlightedText {
    func defaultFont(_ font: Font) -> Self {
        var view = self
        view.defaultFount = font
        return view
    }

    func highlightedFont(_ font: Font) -> Self {
        var view = self
        view.highlightedFont = font
        return view
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    Thanks! I was missing declaring view as a variable prior making the change. Another thing is there anyway I could do this but with a ViewModifier instead? Because since I'm working on the highlighted text type, I can only call these functions right after this components is created and before any other modifier is called, otherwise I loose the type and then these methods can't be invoked. – mdonati May 10 '20 at 06:37