Is there a way to set a specific text style in swiftui similar to the way you make a button style?

Viewed 1921

I have made a button style to be used throughout my app but I can't find a way to accomplish this with text so I end up having to add the .font stuff manually every time. I was wondering if there is a way to set it so I can have a consistent way to style text. Here is the code I use to set my button style.

   struct mainPageButtonStyle: ButtonStyle {
        func makeBody(configuration: Configuration) -> some View {
            configuration.label
                .frame(width: 200, height: 60, alignment: .center)
                .overlay(RoundedRectangle(cornerRadius: 25)
                            .stroke(Color(colorManager.secondaryGreen), lineWidth: 8)
                )
                .padding(.all, 20)
        }
    }
1 Answers

There is no ...Style like protocol for Text but you got plenty of other options (maybe Prestyled is not the greatest name but you get the idea):

Separate View

struct PrestyledText: View {
    private let text: String

    init(_ text: String) {
        self.text = text
    }

    var body: some View {
        Text(text)
            .font(.body)
            .foregroundColor(.blue)
    }
}

Modifier

struct Prestyled: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.body)
            .foregroundColor(.blue)
    }
}

Extension

extension View {
    var prestyled: some View {
        self.font(.body).foregroundColor(.blue)
    }
}

// or 

extension View {
    var prestyled: some View {
        self.modifier(Prestyled())
    }
}

Scope Inheritance

VStack {
    Text("Hello")
    Text("There")
}
.font(.body)
.foregroundColor(.blue)

and an example using all of them:

struct ContentView: View {
    var body: some View {
        VStack {
            PrestyledText("Hello")
            Text("Hello").prestyled
            VStack {
                Text("Hello")
                Text("There")
            }
            .font(.body)
            .foregroundColor(.blue)
        }
    }
}
Related