Home > Software design >  SwiftUI TextField color issue with background and foreground
SwiftUI TextField color issue with background and foreground

Time:05-02

I am trying to set background color to my textfield and it seems to be setting fine for padding area around the textfield but not to the actual textfield

struct PrimaryTextField: View {
    var initialText: String
    @Binding var key: String
    var body: some View {
        VStack {
            TextField(initialText, text: $key)
                .padding()
                .font(.title3)
                .frame(maxWidth: .infinity)
                .background(Color("TextFieldBGColor"))
                .cornerRadius(50.0)
                .shadow(color: Color.black.opacity(0.08), radius: 60, x: 0.0, y: 16)
                .accentColor(Color("AccentColor"))
                .textFieldStyle(.roundedBorder)
        }
    }
}

Above is the coded i used. Below are the images Light mode dark mode

How to make the white text field to be gray colored textfield (in light mode)?

I tried foreground color to TextFieldBGColor but it is changing the color of text in the text field which i dont want to change.

CodePudding user response:

SwiftUI's TextField holds a TextFieldStyle property which controls certain aspects of the UI of the TextField - this is what is responsible for the border and added background on your TextView. Not sure if this is exactly the effect that you're looking for, but you can simply add the modifier .textFieldStyle to your TextField to remove the added styling, which will remove the TextField's background color. If you want the border that was originally there, you may have to add that back as custom using the .background modifier.

TextField(initialText, text: $key)
            .textFieldStyle(.plain)      <------ Added here
            .padding()
            .font(.title3)
            .frame(maxWidth: .infinity)
            .background(Color("TextFieldBGColor"))
            .cornerRadius(50.0)
            .shadow(color: Color.black.opacity(0.08), radius: 60, x: 0.0, y: 16)
            .accentColor(Color("AccentColor"))
            .textFieldStyle(.roundedBorder)

Read more on the TextFieldStyle protocol here:

https://developer.apple.com/documentation/swiftui/textfieldstyle

  • Related