Hiding the Keyboard on button click?

Fahim Parkar picture Fahim Parkar · Mar 20, 2013 · Viewed 11.5k times · Source

I am creating iPhone app which I show below.

At the end of screen I have text field. I have added a delegate for the same. As it is number pad, I have added button seperately so that when button is clicked, they keyboard is hidden.

Below is the code I have:

.h

@interface SearchViewController : UIViewController<UITextFieldDelegate>

@property (retain, nonatomic) IBOutlet UITextField *textField006;
@property (retain, nonatomic) IBOutlet UIButton *doneButton;
- (IBAction)doneAction:(id)sender;

.m

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"textFieldShouldReturn");
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"textFieldDidBeginEditing");
    // Ensure the relevant text field is visible
    CGAffineTransform translation = CGAffineTransformIdentity;
    CGRect screenBound = [[UIScreen mainScreen] bounds];
    CGSize screenSize = screenBound.size;
    CGFloat screenHeight = screenSize.height;

    if (screenHeight==480 || screenHeight==568) {
            translation = CGAffineTransformMakeTranslation(0, -120);
        doneButton.hidden = NO;
        NSLog(@"line 3");
        [UIView beginAnimations:nil context:nil];
        self.view.transform = translation;
        [UIView commitAnimations];
    }
}

- (IBAction)doneAction:(id)sender {
    doneButton.hidden = NO;    
    doneButton.hidden = YES;
    [textField006 resignFirstResponder];
    [UIView beginAnimations:nil context:nil];
    self.view.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];
    [self.textField006 resignFirstResponder];

}

Why isn't the keyboard hiding? How can I hide it?

Keyboard == Decimal Pad Return key >> Go Auto-enable Return key = Ticked

Answer

dsgriffin picture dsgriffin · Mar 20, 2013

Be sure to use endEditing: if it's not currently hiding correctly.

About endEditing:

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

"This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to YES, the text field is never even asked; it is forced to resign."

So, the following should work (inside your button click action method):

[self.view endEditing:YES];