Search code examples
swiftswiftui

Unable to type in text field with overlay


I'm trying to design a text field to which I applied an .overlay modifier to have a background. This text field is inside an HStack with an image and the text field itself. Applying the .overlay to have a background makes it unable to type into, whereas without it, I can. Here's the source code:

ZStack {
                Color.black // This sets the entire background to black
                    .ignoresSafeArea()
                VStack(spacing: 0){
                    
                    Spacer()
                    
                    HStack {
                        Image(systemName: "person.text.rectangle.fill")
                            .foregroundStyle(.white)
                        TextField("Display Name...", text: $name)
                            .foregroundStyle(.white)
                        Spacer()
                    }
                    .padding()
                    .overlay(
                        RoundedRectangle(cornerRadius: 10)
                            .foregroundStyle(.gray).opacity(0.2) // Change the color to gray
                    )
                    .padding()
                    
                }
                
            }```

Image of view:


  [1]: https://i.sstatic.net/ZNVQlfmS.png

Solution

  • As the name implies, overlay goes on top and blocks the inputs, whereas background goes in the background.

    So change .overlay(...) to .background(...) to add the desired background to your HStack.