change color of uitextfield not working in swiftui

1.3k Views Asked by At

I am trying to change color of textfield with below code but it is not working. It takes color as white if the it is light theme and for dark theme automatically takes black color. I want to keep it always black.

    var body: some View {

    TextField(self.textFieldTitle ?? "", text: self.$textFieldInput, onEditingChanged: { editing in self.dosomeCode()}, onCommit: { self.someCode()})
                .background(Color.green)
                .foregroundColor(Color.white)
}
2

There are 2 best solutions below

0
On BEST ANSWER

I want to keep it always black.

Use .black color instead

TextField(self.textFieldTitle ?? "", text: self.$textFieldInput, onEditingChanged: { editing in self.dosomeCode()}, onCommit: { self.someCode()})
            .background(Color.green)
            .foregroundColor(Color.black)  // << here !!

demo1demo2

Tested with Xcode 13.2 / iOS 15.2

1
On

You can set the preferredColorScheme to light for this TextField in order to keep its color scheme same on all mode like this

TextField("Title", text: $title)
        .preferredColorScheme(.light) //ColorScheme
        .background(Color.green)
        .foregroundColor(Color.white)