Home > OS >  How to hide code duplication(Text and parameters)? SwiftUI
How to hide code duplication(Text and parameters)? SwiftUI

Time:10-13

I have a simple code that I used three times Text with identical parameters but with different Text. How to avoid code duplication? I used SwiftUI and Xcode 13.4

Text(status)
    .fontWeight(.bold)
    .foregroundColor(Color.white)
    .padding(.leading, 5)
    .padding(.trailing, 5)
    .background(stats)
    .cornerRadius(3)

CodePudding user response:

You can simply DRY it by converting it to a function:

@ViewBuilder func styledText(_ text: LocalizedStringKey) -> some View {
    Text(text)
        .fontWeight(.bold)
        .foregroundColor(Color.white)
        .padding(.leading, 5)
        .padding(.trailing, 5)
        .background(stats)
        .cornerRadius(3)
}

Then use it like:

styledText(status)

CodePudding user response:

You can create a custom ViewModifier for your Text.

struct CustomTextStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .fontWeight(.bold)
            .foregroundColor(Color.white)
            .padding(.leading, 5)
            .padding(.trailing, 5)
            .background(.black)
            .cornerRadius(3)
    }
}

You can create an extension of View like this to use the above ViewModifier.

extension View {
    func customTextStyle() -> some View {
        modifier(CustomTextStyle())
    }
}

Now set this ViewModifier to your Text.

Text("Hello World")
    .customTextStyle()
  • Related