简体   繁体   中英

SwiftUI, cannot dismiss sheet after the keyboard

In SwiftUI, I open a CommentsView sheet like this:

@State private var selectedCategory: Category?

Button(category.name) {
    selectedCategory = category
}
.sheet(item: $selectedCategory) { category in
    CommentsView(category: category)
}

CommentsView :

struct CommentsView: View {
    @Environment(\.presentationMode) private var presentationMode
    @State private var enteredComment: String = ""
    
    let category: Category
    
    var body: some View {
        VStack {
            TextField("Add a comment", text: $enteredComment)
                .textFieldStyle(RoundedBorderTextFieldStyle())

            Button("Close") {
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

The problem is: I cannot dismiss the CommentsView after I focus on the text field and see the keyboard. Before focusing the "Close" button works as expected.

Change the position of .sheet to be at the top VStack/HStack or ZStack, NOT at the Button View

.sheet(item: $selectedCategory) { category in
    CommentsView(category: category)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM