Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the keyboard disappear programmatically in iOS

I am having trouble getting the keyboard to disappear after entering text. I have many solutions for previous versions of Xcode, but nothing for Xcode 7. My current ViewController.h file looks like:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *txtUsername;
@property (strong, nonatomic) IBOutlet UITextField *txtPassword;

@end

My .m file looks like:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize txtUsername;
@synthesize txtPassword;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.txtUsername.delegate = self;
    self.txtPassword.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

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

@end

I have assigned the delegate from the textField to the ViewController as well.

Update The View I was working with was not assigned to the ViewController class and therefore did not inherit the textFielfShouldReturn method I needed.

like image 274
BlackAperture Avatar asked Sep 13 '25 19:09

BlackAperture


1 Answers

Try:

[self.view endEditing:YES];
like image 136
Mário Cosme Avatar answered Sep 16 '25 07:09

Mário Cosme