onTapGesture禁用我的“选择器”和“细分”点击

时间:2020-04-15 20:25:31

标签: ios swiftui gesture picker

我正在使用Form创建一个SwiftUI。在我的Form中,我有一个DatePickerTextField和一个SegmentedPickerStyle

我的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)

                }
            }
    }
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

您将要使用一些UIKit来完成此操作。

首先,创建一个自定义手势识别器:

    class CloseKeyboardGestureRecognizer: UIGestureRecognizer {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        // Don't run if the tap is in a TextField, since the keyboard shouldnt hide when tapping a textfield.
        guard let touch = touches.first?.view, touch is UITextField else {
            state = .began
            return
        }
            state = .failed
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
       state = .ended
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
        state = .cancelled
    }
}

extension CloseKeyboardGestureRecognizer: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}

然后在SceneDelegate中的场景(_:willConnectTo:options :)中添加:

        let gesture = CloseKeyboardGestureRecognizer(target: window, action:#selector(UIView.endEditing))
        gesture.delegate = gesture
        gesture.cancelsTouchesInView = false
        gesture.requiresExclusiveTouchType = false

        window.addGestureRecognizer(gesture)
    }

这是一种行为,即在文本字段外部点击会关闭键盘,而不会影响其他元素上的点击。