Reiner Fischer
Reiner Fischer

Reputation: 199

SwiftUI Textfield - How to set the background Color for textfield in edit mode to clear

To fit in with my other controls, my TextField views have frames which have a larger height than the text itself.

The standard view is shown in the top of the image with a custom placeholder.

When I tap on the TextField, the smaller text area itself has a gray background, as shown in the bottom of the image.

TextView example

How do I set this text background to a clear color?

struct TestView: View {
    
    @State var city: String
    @State var street: String
    
    var body: some View {
        VStack{
            ZStack(alignment: .center) {
                if city.isEmpty { Text("Bitte Namen eingeben")
                    .font(.system(size: 24, weight: .heavy, design: .default))
                    .foregroundColor(Color( red: 1.0, green: 0.0, blue: 0.0, opacity: 0.3))
                }
            TextField("", text: self.$city)
                .textFieldStyle(CustomTFStyle())
            }
            
            ZStack(alignment: .center) {
                if street.isEmpty { Text("Bitte Strasse eingeben")
                    .font(.system(size: 24, weight: .heavy, design: .default))
                    .foregroundColor(Color( red: 1.0, green: 0.0, blue: 0.0, opacity: 0.3))
                }
            TextField("", text: self.$street)
                .textFieldStyle(CustomTFStyle())
            }
        }
    }
}

public struct CustomTFStyle : TextFieldStyle {
    public func _body(configuration: TextField<Self._Label>) -> some View {
        configuration
            .accentColor(.black)
                .frame(width: 300, height: 70, alignment: .center)
                .border(Color.gray, width: 4)
             .font(.system(size: 30, weight: .heavy, design: .default))
            .clipShape(RoundedRectangle(cornerRadius: 12))
            .shadow(radius: 12)
            .foregroundColor(.black)
            
    }
}

Upvotes: 3

Views: 6619

Answers (2)

Reiner Fischer
Reiner Fischer

Reputation: 199

"UIScrollView.appearance().backgroundColor = .lightGray" in the init method of my rootview does also effect the Textfield behavior. Deleting this line did the trick.

Upvotes: 5

Jordan
Jordan

Reputation: 31

Wasn't able to reproduce this. Try cleaning your project and quitting/restarting Xcode.

Try adding the modifier to your CustomTFStyle:

.background(Color.clear)

Sidenote: You also may want to consider assigning an AttributedString as a placeholder instead of conditionally ZStack'ing a separate Text on top of the TextField 😉

For that you will need to wrap an UITextField in a UIViewRepresentable and do the classic work inside the makeUIView method.

Upvotes: 0

Related Questions