Kevin Vu
Kevin Vu

Reputation: 59

SwiftUI iOS 15 Keyboard toolbar doesn't show for textfield

I'm pretty new to SwiftUI, trying to teach myself a few things here and there. But there's this one issue that's been eating at me for a while... and I can't figure out why the toolbar doesn't work/show for me.

The sample code is below, but the button doesn't show nor is there an actual bar. I have iOS 15.2, with XCode 13.2 beta.

TextField("placeholder", text: $text)
.toolbar {
   ToolbarItemGroup(placement: .keyboard) {
       HStack {
           Button(action: {
               hideKeyboard()
           }) {
               Text("Done")
           }
       }
   }
}

EDIT:

Figured out the reason why... it just wouldn't work in a scroll view for some reason. Anyone know why?

Upvotes: 4

Views: 3399

Answers (2)

Eric  DeLabar
Eric DeLabar

Reputation: 309

Xcode 13.3 (release version), in order for the toolbar to show up, the TextField and the .toolbar need to be inside of a NavigationView.

In my particular case I didn't want a NavigationBar, so I ended up with something like this to make it work:

var body: some View {
    NavigationView {
        VStack {
            TextField("Enter your name", text: $text)
            // Additional text fields go here, all text fields will get the toolbar.
        }
        .navigationTitle("")
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                Spacer()
                Button("Dismiss") {
                    print("Dismiss keyboard...")
                }
            }
        }
    }
}

Upvotes: 1

Joannes
Joannes

Reputation: 2940

Under iOS 15.2 - Xcode 13.2 (not beta).

struct ContentView: View {
    @State var text: String = ""
    
    var body: some View {
        NavigationView {
            VStack {
                Text(text)
                TextField("Enter your name", text: $text)
            }
            .padding()
            .navigationTitle("SwiftUI")
            .toolbar {
//                ToolbarItem(placement: .keyboard) {
//                    Button("Ok") {
//                        print("ok")
//                    }
//                }
                ToolbarItemGroup(placement: .keyboard) {
                    HStack {
                        Button("Press Me") {
                            print("Pressed")
                        }
                        Spacer()
                        Button(action: {
                            print("done")
                        }) { Text("Done") }
                    }
                }
            }
        }
    }
}

Make sure you put everything in a VStack or similar. keyboard

Upvotes: 4

Related Questions