0
votes

I have the following XIB file presented (.custom) when a button is pressed.

@IBAction func contactUsBtnPressed(_ sender: Any) {
            let contactUs = ContactUsXIB()
            contactUs.modalPresentationStyle = .custom
            present(contactUs, animated: false, completion: nil)
        }

enter image description here You'll notice in the top right corner there is a close button. I have assigned the following code to this button:

@IBAction func closeBtnPressed(_ sender: Any) {
        dismiss(animated: false, completion: nil)
    }

This works fine.

For each of the UITextFields, I want the keyboard to dismiss if the user taps anywhere else on the screen. I implemented this code in the swift file to do so: (this dismiss keyboard/view.endEditing(true) code has worked many times for me in other apps)

import UIKit

class ContactUsXIB: UIViewController {

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var telephoneField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()

    }

    @IBAction func closeBtnPressed(_ sender: Any) {
        dismiss(animated: false, completion: nil)
    }

    func setupView() {
        let tap: UIGestureRecognizer = UIGestureRecognizer(target: self, action: #selector(ContactUsXIB.dismissKeyboard))
        view.addGestureRecognizer(tap)     
    }

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

However when I implement this feature, the close button does not work nor does the dismiss keyboard. Here is the incorrect behaviour I now have:

  1. XIB is presented, tap close button - No response

    tap a text field - XIB is dismissed

  2. XIB is presented

    tap a text field, tap anywhere else to dismiss keyboard - no response

    tap close button - no response

    tap a text field - XIB is dismissed

Any idea how to solve?

1

1 Answers

1
votes
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}