onTapGesture отключает мой кран выбора и сегмента - PullRequest
0 голосов
/ 15 апреля 2020

Я создаю Form, используя SwiftUI. В моем Form у меня есть DatePicker, TextField и 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 ]

1 голос
/ 16 апреля 2020

удалите .onTapGesture и добавьте это в форму:

.gesture(DragGesture().onChanged{_ in UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)})
0 голосов
/ 16 апреля 2020

Вы захотите сделать это с некоторыми вещами 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)
    }

Это поведение, при котором нажатие за пределы текстового поля закрывает клавиатуру без воздействия на другие элементы.

...