[英]SwiftUI List onTapGesture covered NavigationLink
I want to hide keyboard when tapped the list background, but onTapGesture will cover NavigationLink.我想在点击列表背景时隐藏键盘,但 onTapGesture 会覆盖 NavigationLink。 Is this a bug or have a better solution?这是一个错误还是有更好的解决方案?
struct ContentView: View {
@State var text: String = ""
var body: some View {
NavigationView {
List {
NavigationLink("NextPage", destination: Text("Page"))
TextField("Placeholder", text: $text)
}
.onTapGesture {
// hide keyboard...
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
}
Thanks!谢谢!
update更新
Thanks to asperi, and I found an alternative way: just put it in section header.感谢 asperi,我找到了另一种方法:只需将其放在 header 部分即可。 As for style, we should create a custom ButtonStyle for NavigationLink.至于样式,我们应该为 NavigationLink 创建一个自定义的 ButtonStyle。
Here is an example of using InsetGroupedListStyle.这是使用 InsetGroupedListStyle 的示例。
struct ContentView: View {
@State var text: String = ""
var body: some View {
NavigationView {
List {
Section(
header: NavigationLink(destination: Text("Page")) {
HStack {
Text("NextPage")
.font(.body)
.foregroundColor(Color.primary)
Spacer()
Image(systemName: "chevron.forward")
.imageScale(.large)
.font(Font.caption2.bold())
.foregroundColor(Color(UIColor.tertiaryLabel))
}
.padding(.vertical, 12)
.padding(.horizontal)
}
.textCase(nil)
.buttonStyle(CellButtonStyle())
.clipShape(RoundedRectangle(cornerRadius: 10))
.padding(.horizontal, -16)
) {}
TextField("Placeholder", text: $text)
}.listStyle(InsetGroupedListStyle())
.onTapGesture {
// hide keyboard...
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
}
}
struct CellButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(
configuration.isPressed
? Color(UIColor.systemGray5)
: Color(UIColor.secondarySystemGroupedBackground)
)
}
}
Here is a possible direction to solve this - by making all taps handled simultaneously and navigate programmatically.这是解决此问题的一个可能方向 - 通过同时处理所有水龙头并以编程方式导航。 Tested with Xcode 12 / iOS 14.用 Xcode 12 / iOS 14 测试。
truct ContentView: View {
@State var text: String = ""
var body: some View {
NavigationView {
List {
MyRowView()
TextField("Placeholder", text: $text)
}
.simultaneousGesture(TapGesture().onEnded {
// hide keyboard...
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
})
}
}
}
struct MyRowView: View {
@State private var isActive = false
var body: some View {
NavigationLink("NextPage", destination: Text("Page"), isActive: $isActive)
.contentShape(Rectangle())
.onTapGesture {
DispatchQueue.main.async { // maybe even with some delay
self.isActive = true
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.