Lance Samaria
Lance Samaria

Reputation: 19592

Swift iOS Stripe -How to dismiss keyboard when Expiration or CVV fields are Active and card number field is empty

I have 1 stripe textfield that accepts the card number, expiration date, and cvv. I also have a tap gesture recognizer on the view to dismiss the keyboard.

If the card number is empty or improperly filled out (eg. 4 digits instead of 16) and I press the expiration date or cvv fields and then I press outside textfield to dismiss the keyboard, instead if it immediately dismissing it jumps to the card number field, then I have to press outside the textfield again to dismiss the keyboard. Essentially I have to press outside the keyboard twice to dismiss it which looks like a bug.

However if the card number is properly filled out and then I go through the same process I only have to press the outside the textfield once to dismiss the keyboard.

It seems like there is a default on the STPPaymentCardTextField that says "if the card number is invalid and the user tries to dismiss the keyboard from the expiration date or cvv fields then don't dismiss the keyboard, jump to the card number first and only dismiss it from there"

How can I immediately dismiss the keyboard from the expiration date or cvv fields even if the card number is improperly filled out?

import Stripe

let paymentTextField: STPPaymentCardTextField = {
    let stp = STPPaymentCardTextField()
    stp.translatesAutoresizingMaskIntoConstraints = false
    return stp
}()

override func viewDidLoad() {
    super.viewDidLoad()

    paymentTextField.delegate = self

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    view.addGestureRecognizer(tapGesture)
}

@objc fileprivate func dismissKeyboard() {
    view.endEditing(true)
}

Upvotes: 1

Views: 508

Answers (1)

IBAction
IBAction

Reputation: 2207

I don't know how Stripe works, but try this:

override func viewDidLoad() {
    super.viewDidLoad()

    paymentTextField.delegate = self

    setGestureRecognizerDelegate()
}

private func setGestureRecognizerDelegate() {
    let tapOnEmptyPlaceGestureRecognizer = UITapGestureRecognizer(
        target: self,
        action: #selector(tapOnEmptyPlaceGestureCaptured(gesture:)))
    tapOnEmptyPlaceGestureRecognizer.delegate = self
    view.addGestureRecognizer(tapOnEmptyPlaceGestureRecognizer)
}

@objc private func tapOnEmptyPlaceGestureCaptured(gesture: UITapGestureRecognizer) {
    let touchPoint = gesture.location(in: view)

    // Make next code for all your textFields
    if !paymentTextField.point(inside: touchPoint, with: nil) {
        paymentTextField.resignFirstResponder()
    }
}

Also don't forget to make your UIViewController a UIGestureRecognizerDelegate

Upvotes: 1

Related Questions