swiftuikeyboardtoolbardismiss

How dismiss keyboard in a sheet with inherited toolbar+button


A view has a TextField and the keyboard has a "Dismiss Keyboard" button (in the toolbar) to remove focus from the textField and dismiss the keyboard. That works fine but when a sheet appears that also contains a TextField the keyboard inherits the button from the previous view and will not dismiss the sheet's keyboard.

I have tried overwriting with a new ToolbarItemGroup within the sheet but it has no effect. The button references the first view. Is there a way to have each keyboard appearance reference the view within which the relevant TextField is situated?

import SwiftUI

struct ContentView: View {
    @FocusState private var focusedField1: Bool
    @State private var name1 = ""
    @State private var showSheet = false
    
    var body: some View {
        VStack {
            TextField("Hello", text: $name1)
                .focused($focusedField1)
                .textFieldStyle(.roundedBorder)
                .padding()
            Button("Show Sheet") { showSheet = true }
        }
        .toolbar {
            toolBarContent1()
        }
        .sheet(isPresented: $showSheet) {
            MySheet()
        }
    }
    
    @ToolbarContentBuilder func toolBarContent1() -> some ToolbarContent {
        ToolbarItemGroup(placement: .keyboard) {
            Spacer()
            Button {
               print("11111")
               focusedField1 = false
            } label: { Text("Dismiss Keyboard") }
        }
    }
}

struct MySheet: View {
    @Environment(\.dismiss) var dismiss
    @FocusState private var focusedField2: Bool
    @State private var name2 = ""
    
    var body: some View {
        VStack {
            TextField("Hello", text: $name2)
                .focused($focusedField2)
                .textFieldStyle(.roundedBorder)
                .padding()
            Button("Dismiss Sheet") {
                focusedField2 = false
                dismiss()
            }
            .toolbar {
                toolBarContent2()
            }
        }
    }
    
    @ToolbarContentBuilder func toolBarContent2() -> some ToolbarContent {
         ToolbarItemGroup(placement: .keyboard) {
             Spacer()
             Button {
                print("22222")
                focusedField2 = false
             } label: { Text("Dismiss Keyboard") }
         }
    }
}

Solution

  • Your code is fine. To make this work, just put your sheet inside a NavigationView{}. Code is below the image: enter image description here

    .sheet(isPresented: $showSheet) {
            NavigationView {
                MySheet()
            }
    }