将 UIToolBar 添加为自定义视图,其中将完成按钮作为 UIBarButtonItem。
这是将完成按钮添加到任何类型的键盘的更安全和更清洁的方式。创建 UIToolBar 并向其添加完成按钮并设置任何 UITextField 或 UITextView 的 inputAccessoryView。
UIToolbar *ViewForDoneButtonOnKeyboard = [[UIToolbar alloc] init];
[ViewForDoneButtonOnKeyboard sizeToFit];
UIBarButtonItem *btnDoneOnKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneBtnFromKeyboardClicked:)];
[ViewForDoneButtonOnKeyboard setItems:[NSArray arrayWithObjects:btnDoneOnKeyboard, nil]];
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard;
IBAction 完成按钮
- (IBAction)doneBtnFromKeyboardClicked:(id)sender
{
NSLog(@"Done Button Clicked.");
//Hide Keyboard by endEditing or Anything you want.
[self.view endEditing:YES];
}
斯威夫特 3
var ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
var btnDoneOnKeyboard = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneBtnFromKeyboardClicked))
ViewForDoneButtonOnKeyboard.items = [btnDoneOnKeyboard]
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard
功能
@IBAction func doneBtnFromKeyboardClicked (sender: Any) {
print("Done Button Clicked.")
//Hide Keyboard by endEditing or Anything you want.
self.view.endEditing(true)
}