SwiftUI sheet closes itself when keyboard is dismissed

Viewed 283

Problem

As the code shows↓, a sheet is presented when "show sheet" button in Form is tapped. The sheet contains only a TextEditor. When keyboard of the texteditor is dismissed (press the right bottom button in the keyboard), keyboard is dismissed, and the sheet is also dismissed.

I hope the sheet wouldn't be dismissed. Maybe it's a bug of SwiftUI...

Please help me figure out why the sheet is dismissed and how to prevent it.

I'm using iPad Pro iOS 15.4.1. The problem doesn't occur on a simulator.

struct ContentView: View {

    @State var showSheet = false

    @State var input = ""

    var body: some View {
        Form {
            // Section 1
            Section {
                Text("1")
                Text("1")
                Text("1")
                Text("1")
                Text("1")
            }
            // Section 2
            Section {
                Text("1")
                Text("1")
                Text("1")
                Text("1")
                Text("1")
            }
            // Section 3
            Section {
                Text("1")
                Text("1")
                Text("1")
                Text("1")
                Text("1")
            }
            // Section 4
            Section {
                Button {
                    showSheet = true
                } label: {
                    Text("show sheet")
                }
                .sheet(isPresented: $showSheet, onDismiss: {
                    print("dismissed")
                }) {
                    TextEditor(text: $input)
                }
            }
            // Section 5
//            Section {
//                Text("1")
//                Text("1")
//                Text("1")
//                Text("1")
//                Text("1")
//            }
        }
    }
}

Picture

click here to see the gif

What I've tried

  • if remove Section 1 or 2 or 3, the problem doesn't occur
  • if uncomment Section 5, the problem doesn't occur
  • fullScreenCover has the same problem
1 Answers

try putting the .sheet(...) outside the Form, it works for me.

Related