0
votes

When I open the application and click in the UITextField it is being instantly dismissed the first time it is clicked. It does not get dismissed after the first time without clicking outside of the view.

I used this answer: Close iOS Keyboard by touching anywhere using Swift for the code to dismiss the textField when an area outside the textField is tapped. Code:

class SettingsViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self
}


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


func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return false
}
1
what the output you expectedAnbu.Karthik
I would expect the textField to not dismiss automatically when it is first tapped. I would expect the textField to be dismissed when the user taps somewhere else in the screen.Ryan Hampton
can you add your viewcontroller codeAnbu.Karthik
Added all code relating to the textFieldRyan Hampton
are you tried my answer, it always present the keyboard whenever you tapped the textfield, it only dismiss the keyboad when user tap in outside, you need this or elseAnbu.Karthik

1 Answers

0
votes

I think from your question, that you want to dismiss the keyboard when someone taps on the view and not the text field. You can override touches began on your view controller to that end:

import UIKit

class ViewController: UIViewController {

    // MARK: - Properties
    @IBOutlet weak var textField: UITextField!

    // MARK: - Actions
    // will resign any first repsonder on this view contorller
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }

    // MARK: - Lifecycle
    override func viewDidLoad() {
        textField.delegate = self
    }

}

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return false
    }
}

And not have to worry about taps, etc.