ResignFirstResponder from Keyboard AccessoryView Button

In my View i have 3 UITextField, for each of them i created an accessoryView for keyboard as explained by apple.

In my accessoryView i added a button which has to call function "CloseKeyboard". In this function i cant find a way to intercept the UITextField in which keyboard is writing and on which i need to call ResignFristResponder.

To add accessoryView on one field i wrote that code

if (field1.inputAccessoryView == nil) {
    field1.inputAccessoryView = [self createInputAccessoryView];   
}
if (field2.inputAccessoryView == nil) {
    field2.inputAccessoryView = [self createInputAccessoryView];   
}
if (field3.inputAccessoryView == nil) {
    field3.inputAccessoryView = [self createInputAccessoryView];   
}

And here createInputAccessory function:

-(UIView *)createInputAccessoryView {

    CGRect accessFrame = CGRectMake(0.0, 0.0, 20.0, 55.0);

    UIView *inputAccessoryView = [[UIView alloc] initWithFrame:accessFrame];

    UIButton *compButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    compButton.frame = CGRectMake(250.0, 10.0, 60.0, 40.0);

    [compButton setTitle: @"Close" forState:UIControlStateNormal];

    [compButton addTarget:self action:@selector(CloseKeyboard:)

                        forControlEvents:UIControlEventTouchUpInside];

    [inputAccessoryView addSubview:compButton];

return inputAccessoryView; }

How can i implement the "CloseKeyboard" function to be able to resignFirstResponder from active UITextField ?

Thank you for your help!

Answers


As of iOS 2.0 and later, there is an easy way to dismiss the keyboard without having to track the currently active control, or iterating through all the available controls, or using a UITextFieldDelegate.

[self.view endEditing:YES]

From the docs:

endEditing:

Causes the view (or one of its embedded text fields) to resign the first responder status. - (BOOL)endEditing:(BOOL)force

Parameters force Specify YES to force the first responder to resign, regardless of whether it wants to do so. Return Value YES if the view resigned the first responder status or NO if it did not.

Discussion 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.


Need Your Help

Twitter Bootstrap calls them “Badges”, is there another broadly established description for this UI pattern?

notifications message badge

This is what I'm referring to: http://twitter.github.com/bootstrap/components.html#badges