118

I created a UITextField programmatically making the UITextField a property of the viewController. I need to dismiss the keyboard with the return and the touch on the screen. I was able to get the screen touch to dismiss, but pressing return is not working.

I've seen how to do it with storyboards and by allocating and initializing the UITextField object directly without creating it as a property. Possible to do?

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

@property (strong, atomic) UITextField *username;

@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    _username.delegate = self; 
    
    [self.view addSubview:self.username];
    [_username resignFirstResponder];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan:withEvent:");
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

@end
Community
  • 1
  • 1
noobsmcgoobs
  • 2,716
  • 5
  • 32
  • 52

20 Answers20

287

The simple way is to connect the delegate of UITextField to self (self.mytestField.delegate = self) and dismiss the keyboard in the method textFieldShouldReturn using [textField resignFirstResponder];

Another way to dismiss the keyboard is the following:

Objective-C

[self.view endEditing:YES];

Swift:

self.view.endEditing(true)

Put [self.view endEditing:YES]; where you would like to dismiss the keyboard (Button event, Touch event, etc.).

Davy de Vries
  • 4,578
  • 2
  • 14
  • 29
Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144
  • when I connect the delegate, though, I get warnings and/or errors. I've seen your way before, but for some reason can't get it to work.Would these methods go in viewDidLoad? – noobsmcgoobs Sep 12 '13 at 07:27
  • 1
    If you were getting error's when you tried to set the textField delegate to self, then you've probably not added UITextFieldDelegate to the class definition. Specifically ... class ViewController: UIViewController, UITextFieldDelegate { ... – TimWhiting Jul 06 '15 at 18:49
31

Add a delegate method of UITextField like this:

@interface MyController : UIViewController <UITextFieldDelegate>

And set your textField.delegate = self; then also add two delegate methods of UITextField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{   
    return YES;
}

// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
tjpaul
  • 343
  • 3
  • 16
iPatel
  • 46,010
  • 16
  • 115
  • 137
  • We should add, that the above only works, if your controller implements the UITextFieldDelegate like so: `@interface MyController : UIViewController ` – DerWOK Sep 12 '13 at 04:38
  • @iPatel I put those 2 methods in, and also added self.username.delegate = self and [self.username resignFirstResponder] in viewDidLoad. This works for both scenarios I needed. Is that normal or am I using too much code? – noobsmcgoobs Sep 12 '13 at 07:43
31

simply use this in swift to dismiss keyboard:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

Swift 3

UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)
Mudith Chathuranga Silva
  • 7,253
  • 2
  • 50
  • 58
  • 1
    SWIFT 3 `UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)` – miff Apr 17 '17 at 12:43
26

//Hide keyBoard by touching background in view

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}
benka
  • 4,732
  • 35
  • 47
  • 58
Vijay Dokrimare
  • 287
  • 3
  • 6
22

SWIFT 4:

self.view.endEditing(true)

or

Set text field's delegate to current viewcontroller and then:

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

    textField.resignFirstResponder()

    return true

}

Objective-C:

[self.view endEditing:YES];

or

Set text field's delegate to current viewcontroller and then:

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

    return YES;
}
Sam
  • 521
  • 1
  • 6
  • 23
9

In the App Delegate, you can write

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.window endEditing:YES];
}

use this way, you can don`t write too much code.

DKong
  • 91
  • 1
  • 1
7

Try to get an idea about what a first responder is in iOS view hierarchy. When your textfield becomes active(or first responder) when you touch inside it (or pass it the messasge becomeFirstResponder programmatically), it presents the keyboard. So to remove your textfield from being the first responder, you should pass the message resignFirstResponder to it there.

[textField resignFirstResponder];

And to hide the keyboard on its return button, you should implement its delegate method textFieldShouldReturn: and pass the resignFirstResponder message.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
Zen
  • 3,047
  • 1
  • 20
  • 18
7

Here's what I use in my code. It works like a charm!

In yourviewcontroller.h add:

@property (nonatomic) UITapGestureRecognizer *tapRecognizer;

Now in the .m file, add this to your ViewDidLoad function:

- (void)viewDidLoad {
    [super viewDidLoad];

    //Keyboard stuff
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    tapRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapRecognizer];
}

Also, add this function in the .m file:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}
owenfi
  • 2,471
  • 1
  • 24
  • 37
Takide
  • 335
  • 3
  • 10
  • 1
    just remember the action:@selector should call the same method name where you do endEditing:YES, in this case "handleSingleTap:" – Marcos Reboucas Jun 25 '15 at 14:30
5

For a group of UITextViews inside a ViewController:

Swift 3.0

for view in view.subviews {
    if view is UITextField {
        view.resignFirstResponder()
    }
}

Objective-C

// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        // no need to cast
        [view resignFirstResponder];
    }
}
Matias Elorriaga
  • 8,880
  • 5
  • 40
  • 58
4

To dismiss a keyboard after the keyboard has popped up, there are 2 cases,

  1. when the UITextField is inside a UIScrollView

  2. when the UITextField is outside a UIScrollView

2.when the UITextField is outside a UIScrollView override the method in your UIViewController subclass

you must also add delegate for all UITextView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
  1. In a scroll view, Tapping outside will not fire any event, so in that case use a Tap Gesture Recognizer, Drag and drop a UITapGesture for the scroll view and create an IBAction for it.

to create a IBAction, press ctrl+ click the UITapGesture and drag it to the .h file of viewcontroller.

Here I have named tappedEvent as my action name

- (IBAction)tappedEvent:(id)sender {
      [self.view endEditing:YES];  }

the abouve given Information was derived from the following link, please refer for more information or contact me if you dont understand the abouve data.

http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/

3

Since the tags only say iOS i will post the answer for Swift 1.2 and iOs 8.4, add these in your view controller swift class:

// MARK: - Close keyboard when touching somewhere else
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true)

}

// MARK: - Close keyboard when return pressed
func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    return true
}
// MARK: -

Also do not forget to add UITextFieldDelegate in the class declaration and set your text fields delegate to self (the view).

Juan Boero
  • 6,281
  • 1
  • 44
  • 62
3

IN Swift 3

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

OR

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == yourtextfieldName
        {
            self.resignFirstResponder()
            self.view.endEditing(true)
        }
    }
Amul4608
  • 1,390
  • 14
  • 30
2

First you need to add textfield delegete in .h file. if not declare (BOOL)textFieldShouldReturn:(UITextField *)textField this method not called.so first add delegate and write keyboard hide code into that method.

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

try this one..

Jitendra
  • 5,055
  • 2
  • 22
  • 42
2

So here's what I did to make it dismiss after touching the background or return. I had to add the delegate = self in viewDidLoad and then also the delegate methods later in the .m files.

.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>


@property (strong, atomic) UITextField *username;

@end

.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    self.username.delegate = self;
    [self.username resignFirstResponder];
    [self.view addSubview:self.username];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}



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

@end
noobsmcgoobs
  • 2,716
  • 5
  • 32
  • 52
2

Simply use this in Objective-C to dismiss keyboard:

[[UIApplication sharedApplication].keyWindow endEditing:YES];
Linc
  • 1,279
  • 12
  • 16
0

Add Delegate : UITextFieldDelegate

@interface ViewController : UIViewController <UITextFieldDelegate>

and then add this delegate method

// This should work perfectly

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
Ravi_Parmar
  • 12,319
  • 3
  • 25
  • 36
0
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
    if ([obj isKindOfClass:[UITextField class]]) {
        [obj resignFirstResponder];
    }
}];
}

when you using more then one textfield in screen With this method you doesn't need to mention textfield every time like

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];
Harshad
  • 2,361
  • 2
  • 18
  • 24
0

Swift 2 :

this is what is did to do every thing !

close keyboard with Done button or Touch outSide ,Next for go to next input.

First Change TextFiled Return Key To Next in StoryBoard.

override func viewDidLoad() {
  txtBillIdentifier.delegate = self
  txtBillIdentifier.tag = 1
  txtPayIdentifier.delegate  = self
  txtPayIdentifier.tag  = 2

  let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
  self.view.addGestureRecognizer(tap)

}

func textFieldShouldReturn(textField: UITextField) -> Bool {
   if(textField.returnKeyType == UIReturnKeyType.Default) {
       if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
           next.becomeFirstResponder()
           return false
       }
   }
   textField.resignFirstResponder()
   return false
}

func onTouchGesture(){
    self.view.endEditing(true)
}
Mojtaba Yeganeh
  • 2,788
  • 1
  • 30
  • 49
0

If you don't know current view controller or textview you can use the Responder Chain:

UIApplication.shared.sendAction(#selector(UIView.endEditing(_:)), to:nil, from:nil, for:nil)
coldfire
  • 946
  • 10
  • 8
0

for swift 3-4 i fixed like

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

just copy paste anywhere on the class. This solution just work if you want all UItextfield work as same, or if you have just one!

hall.keskin
  • 201
  • 3
  • 6