onTapGesture 禁用我的选取器和分段点击

Luk*_*vin 4 picker gesture ios swiftui

我正在创建一个Form使用SwiftUI. 在我的内部Form,我有一个DatePicker,,TextField和一个SegmentedPickerStyle

TextField正在使用 a .decimalPad,我正在尝试找到完成打字后关闭键盘的最佳方法。

我尝试添加 a.onTapGesture但它阻止我使用任何选择器。当我点击它们时什么也没有发生。

这是我正在尝试做的事情:

struct ContentView: View {
    @State var date = Date()

    @State var price = ""
    @State private var tipPercentage = 2

    let tipPercentages = [10, 15, 20, 25, 0]

    var body: some View {
            NavigationView {
                Form {
                    Section {
                        DatePicker(selection: $date, displayedComponents: .date) {
                            Text("Date").bold().foregroundColor(Color.init(red: 100.0/255.0, green: 208.0/255.0, blue: 100.0/255.0))
                        }

                        HStack {
                            Text("Price"))
                            Spacer()
                            TextField("required", text: $price).multilineTextAlignment(.trailing).keyboardType(.decimalPad)
                        }
                    }

                    Section(header: Text("How much tip do you want to leave?")) {
                        Picker("Tip percentage", selection: $tipPercentage) {
                            ForEach(0 ..< tipPercentages.count) {
                                Text("\(self.tipPercentages[$0])%")
                            }
                        }
                        .pickerStyle(SegmentedPickerStyle())
                    }
                }
                .onTapGesture {
                       let keyWindow = UIApplication.shared.connectedScenes
                                          .filter({$0.activationState == .foregroundActive})
                                          .map({$0 as? UIWindowScene})
                                          .compactMap({$0})
                                          .first?.windows
                                          .filter({$0.isKeyWindow}).first
                       keyWindow!.endEditing(true)

                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

wor*_*dog 5

删除 .onTapGesture 并将其添加到表单中:

.gesture(DragGesture().onChanged{_ in UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)})
Run Code Online (Sandbox Code Playgroud)