I am making a universal app that has a UITextView. When the app run on the iPad there is a button on the lower right which enables me to dismiss the keyboard. The iPhone version does not have such a button. I have seen on some iPhone apps a bar on top of the keyboard that has a done option. Is there an easy way to add an iPad style dismiss keyboard button to the iPhone app as well. If not, what is the best way to add a done style bar to the top of the keyboard? Thanks in advance.
This is a really common feature in almost all iOS apps, so it's good to have a ready copy-paste solution. To achieve the adding of a keyboard Done button we need to use UIToolbar. UIToolbar is a control that displays one or more buttons along the bottom edge of your interface.
An easy trick to have a Done button signed: true, decimal: true), maxLength: 10, inputFormatters: [FilteringTextInputFormatter.
Please try this code
//set up a placeholder variable for the textfield user typing
UITextView *currentTextView;
-(void)addDoneToolBarToKeyboard:(UITextView *)textView
{
UIToolbar* doneToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
doneToolbar.barStyle = UIBarStyleBlackTranslucent;
doneToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonClickedDismissKeyboard)],
nil];
[doneToolbar sizeToFit];
textView.inputAccessoryView = doneToolbar;
}
//remember to set your text view delegate
//but if you only have 1 text view in your view controller
//you can simply change currentTextField to the name of your text view
//and ignore this textViewDidBeginEditing delegate method
- (void)textViewDidBeginEditing:(UITextView *)textView
{
currentTextView = textView;
}
-(void)doneButtonClickedDismissKeyboard
{
[currentTextView resignFirstResponder];
}
and add this in your view did load
[self addDoneToolBarToKeyboard:self.textView];
Hope that helps
same answer swift3 :
func addDoneToolBarToKeyboard(textView:UITextView)
{
let doneToolbar : UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50))
doneToolbar.barStyle = UIBarStyle.default
let flexibelSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let hideKeyboardItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.dismissKeyboard))
doneToolbar.items = [flexibelSpaceItem, hideKeyboardItem!]
doneToolbar.sizeToFit()
textView.inputAccessoryView = doneToolbar
}
and dismiss function will be:
func dismissKeyboard()
{
self.view.endEditing(true)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With