LiTHiUM2525
LiTHiUM2525

Reputation: 307

Why isn't my keyboard disappearing when I press the RETURN key?

This is my SecondViewController Class :

class SecondViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var txtNewItem: UITextField!
@IBOutlet weak var lblResult: UILabel!
@IBAction func btnAddNewItem(_ sender: Any) {
    let itemsObject = UserDefaults.standard.object(forKey: "items")
    var items:[String]

    if let tmpItem = itemsObject as? [String] {
        if txtNewItem.text == "" {
            //Alert message if empty txtNewItem is ""            
        } else {
            items = tmpItem
            items.append(txtNewItem.text!)
            UserDefaults.standard.set(items, forKey: "items")
        }
    } else {
        items = [txtNewItem.text!]
        UserDefaults.standard.set(items, forKey: "items")
    }
    txtNewItem.text = ""
}

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

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
    }
}

The 2 functions (touchesBegan and textFieldShouldReturn) working perfectly into my FisrtViewController and many others apps.

I don't know why in this case, if I click everywhere the keyboard disappears and is working fine but, when I press the return key, the keyboard does NOT disappear.

I tested it on XCode simulator and on my iPhone 7 and iPad Air 2 the problem continue on this 3 iDevices.

N.B: I voluntary deleted the viewDidLoad and didReceiveMemoryWarning because I don't have code into these functions.

Upvotes: 0

Views: 1261

Answers (1)

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

You must add these lines of code:

override func viewDidLoad(){
    super.viewDidLoad()
    self.txtNewItem.delegate = self
}

Into viewDidLoad() in order for this to work! Now it assigns your class to the textField's delegate. Glad it helped!

Upvotes: 2

Related Questions