Ios – How to hide keyboard in swift on pressing return key

iosswiftuitextfield

I am using UITextfied while clicking on textfied keyboard appear but when i pressed the return key, keyboard is not disappearing. I used the following code:

func textFieldShouldReturn(textField: UITextField!) -> Bool // called when 'return' key pressed. return NO to ignore.
{
    return true;
}

the method resignfirstresponder is not getting in function.

Best Answer

You can make the app dismiss the keyboard using the following function

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return false
}

Here is a full example to better illustrate that:

//
//  ViewController.swift
//
//

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var myTextField : UITextField

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.myTextField.delegate = self
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
}

Code source: http://www.snip2code.com/Snippet/85930/swift-delegate-sample