[英]SwiftUI (dismiss-keyboard) overlay disables underlying actions
This question is related to How to hide keyboard when using SwiftUI?这个问题与使用 SwiftUI 时如何隐藏键盘有关?
Sample Code:示例代码:
struct ContentView: View {
@State var text = ""
var body: some View {
Background {
NavigationView {
List {
TextField("TextInput", text: $text)
Text("OnTapGesture")
.onTapGesture {
print("Text Tapped") //works
}
Button("Tap me") {
print("Btn Tapped") //doesn't work
}
NavigationLink("Go to detail", destination: Text("DetailView")) //doesn't work
}
}
}
}
}
struct Background<Content: View>: View {
private var content: Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content()
}
var body: some View {
Rectangle()
.overlay(content)
.onTapGesture {
self.endEditing()
}
}
func endEditing() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
The overlay here works as expected that I can tap anywhere to dismiss the keyboard.这里的覆盖按预期工作,我可以点击任何地方来关闭键盘。 However, by adding onTapGesture
on the overlay certain other actions don't work anymore.但是,通过在叠加层上添加onTapGesture
某些其他操作不再起作用。 Is this intended?这是故意的吗? Is it a bug?这是一个错误吗? Is there a way to work around that?有没有办法解决这个问题?
Found a one-liner solution, inspired by SwiftUI: How to dismiss the keyboard by tap on NavigationLink?找到了一个单线解决方案,灵感来自SwiftUI:如何通过点击 NavigationLink 来关闭键盘?
.gesture(DragGesture(minimumDistance: 20, coordinateSpace: .local).onChanged{_ in endEditing() })
This will keep all actions enabled (including delete gestures) and dismisses the keyboard when scrolling...这将保持启用所有操作(包括删除手势)并在滚动时关闭键盘......
Add this modifier to the button将此修饰符添加到按钮
Button(action: {}) {
Text("Button Tap")
}
.buttonStyle(PlainButtonStyle())
Complete Code完整代码
struct ContentView: View {
@State var text = ""
@State private var tap: Bool = false
var body: some View {
Background {
NavigationView {
List {
TextField("TextInput", text: $text)
Text("OnTapGesture")
.onTapGesture {
print("Text Tapped") //works
}
Button(action: buttonTapped) {
Text("Button Tapped")
}
.buttonStyle(PlainButtonStyle())
NavigationLink(destination: Text("DetialView"), isActive: $tap) {
Button(action: tapButton) {
Text("Go to Navigation")
}
.buttonStyle(PlainButtonStyle())
}
}
}
}
}
func buttonTapped() {
print("Button Tapped...")
}
func tapButton() {
tap.toggle()
}
} }
I hope it will work fine我希望它能正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.