How do I cast ViewModifier Content to anticipated type?

Viewed 132

So I think I could be using ViewModifiers incorrectly, but is it possible to cast the Content of a ViewModifier to the anticipated type, e.g. Text? I want to use .fontWeight(.bold) but that is not part of the base/aliastype Content. Alternatively what should I use to achieve this effect? A custom Style function?

struct ButtonTextModifier: ViewModifier {
    func body(content: Content) -> some View {
        (content as Text) //<--- ERROR HERE
            .fontWeight(.bold) //<--- Because I want to use this
            .font(.largeTitle)
            .padding()
    }
}

The error I get:

Cannot convert value of type 'ButtonTextModifier.Content' (aka '_ViewModifier_Content<ButtonTextModifier>') to type 'Text' in coercion

1 Answers

You might have to add a new method on Text by declaring it in it's extension.

extension Text {
    func buttonTextModifier() -> some View {
        self
            .fontWeight(.bold)
            .font(.largeTitle)
            .padding()
    }
}
Related