Lalit_vicky
Lalit_vicky

Reputation: 295

Hide keyboard on ViewWillAppear

i have a screen having navigation controller and text field. when i move next and come back i want the keyboard should be hidden in first screen. I am hiding keyboard like on textfield event.

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

But how to do that in View related events so that whenever my view appears keyboard is hidden.. Pls guide/Help. thanks in adv.

Upvotes: 2

Views: 2618

Answers (5)

Iya
Iya

Reputation: 1918

//This is for Swift
override func viewWillAppear(animated: Bool)
{
   self.view.endEditing(true)
}

Upvotes: 0

Bhavin
Bhavin

Reputation: 27225

A good habit is to write this code in your screen's -viewWillDisappear. So, when you navigate from one screen to another at that time it will remove the keyboard from that screen.

- (void)viewWillDisappear:(BOOL)animated
{
    [self.view endEditing:YES];
    [super viewWillDisappear:animated];
}

For multiple textFields, it is better to use -endEditing for that particular view instead of -resignFirstResponder for any single textField. Take a look at my Answer.

Upvotes: 1

Anuj
Anuj

Reputation: 830

The thing that you are doing wrong is , when you are moving back previous controller to the current controller , the keyboard is up due to the selected textfield of previous controller .

And in the current controller the code:

-(void)viewWillAppear:(BOOL)animated    {
    [super viewWillAppear:animated];
    [[self view] endEditing:YES];
}

It will not work as no textfield is selected at this controller. So what you need to do is write the same code in the previous controller viewWillDisappear Method it will surely resolve your Problem .

- (void)viewWillDisappear:(BOOL)animated
{
    [self.view endEditing:YES];
    [super viewWillDisappear:animated];
}

Upvotes: -1

Buntylm
Buntylm

Reputation: 7373

I think this is also a good way to remove keyboard with in iOS App if your UITextView or UITextField not connected through the IBOutlet.

If you want to Hide Keyboard with UIViewController LifeCycle Events like with viewWillAppear or etc. Follow this

-(void)viewWillAppear:(BOOL)animated    {
    [super viewWillAppear:animated];
    [[self view] endEditing:YES];
}

Otherwise if you object connected using IBOutLet this code will work fine as you describe too.

[yourTextField resignFirstResponder];

Upvotes: 4

IronManGill
IronManGill

Reputation: 7226

Add this code to your ViewWillAppear :

for(id obj in self.view.subviews)
    {
        if([obj isKindOfClass:[UITextField class]])
        {
             [obj resignFirstResponder];
        }
    }

This would take in all the textfields in that particular view here it is the whole view and add the code you had written previously for removing the keyboard.

Upvotes: 1

Related Questions