我正在使用Form创建一个SwiftUI。在Form中,我有一个DatePickerTextFieldSegmentedPickerStyle

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

我尝试添加.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)

                }
            }
    }
}

最佳答案

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

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

关于ios - onTapGesture禁用我的“选择器”和“分割”点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61237991/

10-14 23:08