7

Like seriously after going through this...

Easy way to dismiss keyboard?

... I have multiple TextFields and a few TextViews. Is there not a way to a have a batch or group Dismiss First Responder for all text fields? Will I need to make method for each field? Maybe I overlooked something in that link?

Maybe I can follow something like this:

https://stackoverflow.com/questions/3282837/problem-with-multiple-textfields-to-make-the-keyboard-dissapear

Would the latter make sense? Thanks in advance.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

I figured it out....

Controller.h

@interface Controller : UIViewController <UITextFieldDelegate> {
    IBOutlet UITextField *clickedDone;
}
@property (nonatomic, retain) IBOutlet UITextField *clickedDone;

Controller.m

#import "Controller.h"
@implementation Controller
@synthesize clickedDone;

- (void)viewDidLoad
{
    [super viewDidLoad];
    [clickedDone setDelegate:self];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;    
}
Community
  • 1
  • 1
xTHENKx
  • 160
  • 1
  • 8

4 Answers4

31

The view has an endEditing: method you can use. The docs say

Causes the view (or one of its embedded text fields) to resign the first responder status.

In your view controller you can just call:

[[self view] endEditing:YES];
Morten Fast
  • 6,222
  • 24
  • 36
4
clickedDone.returnKeyType = UIReturnKeyDone;  // in viewDidLoad

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
   [textField resignFirstResponder];
   return YES;    
}
Surjit Joshi
  • 2,719
  • 2
  • 16
  • 20
2

Its very easy now. You can follow different approach depending on your use cases. In my case I had multiple textfields in UITableViewController. What I did is this :

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.view endEditing:YES];
}
Ajith R Nayak
  • 4,436
  • 3
  • 32
  • 39
Saleh Masum
  • 1,977
  • 1
  • 15
  • 16
1

Best answer is:

  1. Added UITextFieldDelegate protocol to your viewcontroller @interface ViewController : UIViewController
  2. In your xib, select the textField, in your Ulitlites section in the right side pane of XCode in the subsection of "Connections Inspector", link the textField's delegate with the .xib's "File's Owner".
  3. In your Viewcontroller implementation, include the follwing

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
   [textField resignFirstResponder];
   return YES;    
}
Andrew Barber
  • 37,547
  • 20
  • 91
  • 118
ejps
  • 79
  • 3