SwiftUI列表onTapGesture涵盖了NavigationLink

问题描述

我想在点击列表背景时隐藏键盘,但是onTapGesture将涵盖NavigationLink。这是错误还是有更好的解决方案?

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)
            }
        }
    }
}

谢谢!

更新

感谢asperi,我发现了另一种方法:只需将其放在节标题中即可。至于样式,我们应该为NavigationLink创建一个自定义的ButtonStyle。

这里是使用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),for: nil)
            }
        }
    }
}

struct CellButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .background(
                configuration.isPressed
                    ? Color(UIColor.systemGray5)
                    : Color(UIColor.secondarySystemGroupedBackground)
            )
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)