skip to Main Content

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)

2

Answers


  1. 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()
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search