Vins Vins - 3 months ago 20
iOS Question

Add a button to hide keyboard

On a UITextView to hide the keyboard, there is the method:

...
textfield.returnKeyType = UIReturnKeyDone;
textfield.delegate = self;
....

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

}


but if I want to leave the button "done" to the "return" and add a button to hide the keyboard, how do I?

Answer

You can assign a toolbar with a button that dismisses the keyboard as the text field's inputAccessoryView. A quick example would be,

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:@selector(resignFirstResponder)] autorelease];
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];
toolbar.items = [NSArray arrayWithObject:barButton];

textField.inputAccessoryView = toolbar;