[ios] How to hide the keyboard when I press return key in a UITextField?

Clicking in a textfield makes the keyboard appear. How do I hide it when the user presses the return key?

This question is related to ios objective-c cocoa-touch delegates

The answer is


Try this,

[textField setDelegate: self];

Then, in textField delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

You can connect "Primary Action Triggered" (right click on UITextField) with an IBAction and you can resign first responder (without delegation). Example (Swift 4):

@IBAction func textFieldPrimaryAction(_ sender: UITextField) {
    sender.resignFirstResponder()
    ...
}

In swift do like this:
First in your ViewController implement this UITextFieldDelegate For eg.

class MyViewController: UIViewController, UITextFieldDelegate {
....
}

Now add a delegate to a TextField in which you want to dismiss the keyboard when return is tapped either in viewDidLoad method like below or where you are initializing it. For eg.

override func viewDidLoad() {

    super.viewDidLoad()   
    myTextField.delegate = self
}

Now add this method.

func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}

Swift 4

Set delegate of UITextField in view controller, field.delegate = self, and then:

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // don't force `endEditing` if you want to be asked for resigning
        // also return real flow value, not strict, like: true / false
        return textField.endEditing(false)
    }
}

[textField resignFirstResponder];

Use this


set delegate of UITextField, and over ride, textFieldShouldReturn method, in that method just write following two lines:

[textField resignFirstResponder];
return YES;

that's it. Before writing a code dont forget to set delegate of a UITextField and set Return key type to "Done" from properties window.(command + shift + I).


Try this in Swift,

Step 1: Set delegate as self to your textField

textField.delegate = self

Step 2: Add this UITextFieldDelegate below your class declaration,

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

Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.

class TextFieldWithReturn: UITextField, UITextFieldDelegate
{

    required init?(coder aDecoder: NSCoder) 
    {
        super.init(coder: aDecoder)
        self.delegate = self
    }

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

}

Then all you need to do in the storyboard is set the fields to use the class:

enter image description here


In viewDidLoad declare:

[yourTextField setDelegate:self];

Then, include the override of the delegate method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.

Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:

extension UIViewController : UITextFieldDelegate {
    ...
}

but the alternative works as well:

class MyViewController: UIViewController {
    ...
}

Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)

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

In your viewDidLoad method, set the textfield's delegate to self

@IBOutlet weak var myTextField: UITextField!
...

override func viewDidLoad() {
    ..
    myTextField.delegte = self;
    ..
}

That should be all. Now, when you press return the textFieldShouldReturn should be called.


If you want to hide the keyboard for a particular keyboard use [self.view resignFirstResponder]; If you want to hide any keyboard from view use [self.view endEditing:true];


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to delegates

Delegates in swift? How can I make a weak protocol reference in 'pure' Swift (without @objc) C# cannot convert method to non delegate type Invoke(Delegate) What is a C++ delegate? How do I set up a simple delegate to communicate between two view controllers? LINQ where clause with lambda expression having OR clauses and null values returning incomplete results C# - using List<T>.Find() with custom objects Func vs. Action vs. Predicate What is Func, how and when is it used