Add a button to hide keyboard
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;
Swift 2.0 version:
//Declared at top of view controllervar accessoryDoneButton: UIBarButtonItem!let accessoryToolBar = UIToolbar(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.width, 44))//Could also be an IBOutlet, I just happened to have it like thislet codeInput = UITextField()//Configured in viewDidLoad()self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.donePressed(_:)))self.accessoryToolBar.items = [self.accessoryDoneButton]self.codeInput.inputAccessoryView = self.accessoryToolBar
Swift 4:
//Declared at top of view controllervar accessoryDoneButton: UIBarButtonItem!let accessoryToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))//Could also be an IBOutlet, I just happened to have it like thislet codeInput = UITextField()//Configured in viewDidLoad()self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePressed))self.accessoryToolBar.items = [self.accessoryDoneButton]self.codeInput.inputAccessoryView = self.accessoryToolBarfunc donePressed() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true)}
This can be done ways easier!
I made a custom view in IB, in my viewController.h I just made an IBOutlet UIView *accessoryView;
, connected them and an - (IBAction)dismissKeyboard;
I put in the view a toolbar with a done button, made a connection to the IBAction an wrote:[textView resignFirstResponder]
and
- (void)viewDidLoad{ textView.inputAccessoryView = accessoryView; [super viewDidLoad];}
But actually that looks a bit strange and non-apple-style… Got an idea?