Hello,
I am trying to create a simple effect in a sheet view where when a user tap the 'Done' button on keyboard, the 'TextField' should be unfocused and the keyboard should disappear. With almost the same code, the 'Done' button doesn't work as expected in 'SheetView' as it does in 'MainView'. Any suggestions are appreciated.
struct MainView: View {
@State private var text = ""
@FocusState private var isFocused: Bool
@State private var showSheet = false
var body: some View {
VStack {
TextField("text", text: $text)
.focused($isFocused)
.textFieldStyle(.roundedBorder)
Button("showSheetView") {
isFocused = false
showSheet.toggle()
}
}
.padding()
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
isFocused = false
}
}
}
.sheet(isPresented: $showSheet) {
NavigationStack {
SheetView()
}
}
}
}
struct SheetView: View {
@Environment(\.dismiss) var dismiss
@State private var text = ""
@FocusState private var isFocused: Bool
var body: some View {
TextField("text", text: $text)
.focused($isFocused)
.textFieldStyle(.roundedBorder)
.padding()
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Cancel") {
isFocused = false
dismiss()
}
}
// The following tool bar button does not work. It seems tappable, but not functioning.
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
isFocused = false
}
}
}
}
}