Keyboard Toolbar buttons not showing
Asked Answered
G

2

12

I am using the example from HWS but I'm having no luck getting buttons to show above the keyboard.

Xcode 13.2.1 / Physical device running iOS 15.3.1

Is this a known issue?

import SwiftUI

struct KeyboardView: View {
    @State private var name = "Neil"

    var body: some View {
        TextField("Enter your name", text: $name)
            .textFieldStyle(.roundedBorder)
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Button("Click me!") {
                        print("Clicked")
                    }
                }
            }
    }
}
Grus answered 21/2, 2022 at 12:41 Comment(4)
So wrapping around a NavigationView allowed me to at least see the button. Feels like a bug. Thanks.Grus
Not a bug. .toolBar has to have a NavigationView to operate. Same for .navigationTitle, NavigationLink(), etc.Bullivant
Logically, it makes no sense that a NavigationView is required for a keyboard toolbar to work. We aren't navigating anywhere. I think it's a bug. And I know that I had this working without a NavigationView a few months ago, but now I can confirm it's not working for me without a NavigationView. (Xcode 13.3.1, iOS 15.4.1)Hufnagel
It does not work if you should a UIViewRepresentable UITextView.Hadwyn
P
9
  1. Put your parent view inside a NavigationStack or NavigationView
  2. Put your text view in a NavigationView (not stack)
struct KeyboardView: View {
    @State private var name = "Neil"

    var body: some View {
        NavigationView {
            TextField("Enter your name", text: $name)
            .textFieldStyle(.roundedBorder)
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Button("Click me!") {
                        print("Clicked")
                    }
                }
            }
        }
    }
}

struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            NavigationStack {
                KeyboardView()
            }
        }
    }
}

Tested on: Xcode 15 beta 5

Perzan answered 6/8, 2023 at 7:8 Comment(0)
S
0

Try out this solution Create a ViewModifier:

 struct DoneToolbar: ViewModifier {
   let doneAction: () -> Void

    @ViewBuilder
    func body(content: Content) -> some View {
      content
      .toolbar {
          ToolbarItem(placement: .keyboard) {
             HStack {
               Spacer()
               Button(action: doneAction) {
                 Text("Done")
                 .fontWeight(.semibold)
                 .foregroundColor(.blue)
         }
       }
     }
   }
 }
}

extension View {
  func doneToolbar(action: @escaping () -> Void) -> some View {
     modifier(DoneToolbar(doneAction: action))
   }
}

Usage:

TextField("Placeholder", text: $text)
  .doneToolBar { 
     // action callback
  }
Salim answered 22/4, 2024 at 17:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.