[英]SwiftUI not dismissing keyboard correctly after navigating away
如果在我上次離開時顯示鍵盤,則在導航堆棧中上升一個級別時,我遇到 SwiftUI 問題。
預期:鍵盤應該仍然顯示或關閉,屏幕上的所有控件都應該按照編程進行響應
觀察到:鍵盤未顯示,但屏幕的下半部分沒有響應,就好像鍵盤仍然在那里阻止點擊輸入一樣
具體在下面的示例代碼中觸發它:
觀察到:“safeAreaInset bottom”視圖移動到屏幕中間。 下面的區域沒有響應水龍頭。
測試於:Xcode 14.1、iOS 16.1,解決方案需要支持iOS 15.0
struct KeyboardDismissSampleView: View {
@Environment(\.dismissSearch) private var dismissSearch
@State var searchText: String = ""
@State var showDetailView = false
var body: some View {
NavigationView {
ScrollView {
NavigationLink(isActive: $showDetailView) {
Text("showDetailView")
} label: {
EmptyView()
}
VStack(alignment: .leading, spacing: 15) {
ForEach(0..<50) { i in
// Version A
// NavigationLink {
// Text("Row \(i)")
// } label: {
// Text("Row \(i)")
// .frame(maxWidth: .infinity, alignment: .leading)
// }
// Version B
Button("Row \(i)") {
// UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
dismissSearch()
showDetailView = true
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding()
}
.safeAreaInset(edge: .bottom, content: {
// This view is just to visually show the issue
// Even without his safeAreaInset section, the area covered by the keyboard is still not responding to taps
Text("safeAreaInset bottom")
.padding()
.frame(maxWidth: .infinity)
.background(Color.yellow)
})
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
}
}
}
我嘗試使用 resignFirstResponder 和 dismissSearch,它們要么有相同的問題,要么引入了其他問題。 此日志顯示在 Xcode 控制台中,顯然您不能同時關閉鍵盤和導航:
pushViewController:animated: called on <_TtGC7SwiftUI41StyleContextSplitViewNavigationControllerVS_19SidebarStyleContext_ 0x10f01c600> while an existing transition or presentation is occurring; the navigation stack will not be updated.
我看過這些相關的問題:
看起來
UIApplication.shared.windows.first?.endEditing(true)
解決了問題,盡管它確實會生成棄用警告。
請注意,我刪除了注釋掉的代碼並將NavigationView
替換為新的NavigationStack
,但這並不是解決問題的方法。
struct ContentView: View {
@State var searchText: String = ""
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
ScrollView {
VStack(alignment: .leading, spacing: 15) {
ForEach(0..<50) { i in
Button("Row \(i)") {
UIApplication.shared.windows.first?.endEditing(true)
path.append(i)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding()
}
.navigationDestination(for: Int.self) { _ in
Text("show detail view")
}
.safeAreaInset(edge: .bottom) {
Text("safeAreaInset bottom")
.padding()
.frame(maxWidth: .infinity)
.background(Color.yellow)
}
}
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.