Ashish Agarwal
Ashish Agarwal

Reputation: 14925

ios - make keyboard disappear when UIButton is pressed

I am trying to make the keyboard disappear when a UIButton is pressed -

-(IBAction)nextButtonPressed{
    [usernameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

I have declared the button as IBOutlet and connected it to the IBAction in the storyboard. But the code however does not work and keyboard remains visible. What am I doing wrong ?

Upvotes: 0

Views: 358

Answers (2)

Carina
Carina

Reputation: 2260

You forgot this:

usernameTextField.delegate = self;
passwordTextField.delegate = self;

Upvotes: 0

Alex Moskalev
Alex Moskalev

Reputation: 607

First you need to subscribe to the UITextFieldDelegate Protocol in your View/ViewController's header file like this:

@interface YourViewController : UIViewController <UITextFieldDelegate>

Make sure you're setting your view/viewcontroller to be the UITextField's delegate after you init the textfield in the .m:

yourTextField.delegate = self;

And you can do this :

-(IBAction)nextButtonPressed{
    [usernameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

Hope it'll help

Upvotes: 1

Related Questions