0

I currently have the following code that represents a TextField with a background and an icon.

struct TextFieldAreaView: View {
    
    @State var query = ""
    
    var body: some View {
        
        HStack {
            
            Image(systemName: "magnifyingglass")
                .padding(.leading, 10)
            
            TextField("Placeholder", text: $query)
                .padding(5)
        }
        .background(Color.black.opacity(0.3))
        .cornerRadius(10)
        .padding()
        
    }
}

Of course, because the background is actually a HStack and the icon an image outside the TextField's frame area, when the user taps on either of those, the keyboard won't show up.

In order for the keyboard to show you must precisely tap on the TextField. This of course is not very intuitive.

Is there any way to make it so that when tapping on the icon or the background HStack the keyboard would show up?

Flerex
  • 324
  • 2
  • 12

1 Answers1

-1

You can try removing the padding or provide a negative for example:

 .padding(.trailing, -100)

Doing this will increase the tappable area. Because by default when you use a padding() it shrinks your text field in all 4 directions top, button, left and right.

Here is an example taken from my project:

  HStack{
        Image(systemName: taskViewModel.task.completed ? "checkmark.circle.fill" : "circle")
            .resizable()
            .frame(width: 20, height:20)
            .onTapGesture {
                self.taskViewModel.task.completed.toggle()
            }
        TextField("Enter the task title", text: $taskViewModel.task.title, onCommit: {
            self.onCommit(self.taskViewModel.task)
            
                
        })
        .padding()
        .padding(.trailing, -100)
Dakata
  • 1,227
  • 2
  • 14
  • 33