添加一个button来隐藏键盘

在UITextView隐藏键盘,有这样的方法:

... textfield.returnKeyType = UIReturnKeyDone; textfield.delegate = self; .... -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } 

但如果我想离开button“完成”到“返回”并添加一个button来隐藏键盘,我该怎么办?

您可以为工具栏指定一个按键,将键盘作为文本inputAccessoryViewinputAccessoryView 。 一个简单的例子是,

 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; 

这可以做到更轻松!

我在IB中做了一个自定义视图,在我的viewController.h我只是做了一个IBOutlet UIView *accessoryView; ,连接它们和一个- (IBAction)dismissKeyboard;

我把视图放在一个带有完成button的工具栏上,与IBActionbuild立了连接: [textView resignFirstResponder]

 - (void)viewDidLoad { textView.inputAccessoryView = accessoryView; [super viewDidLoad]; } 

但实际上,这看起来有点奇怪,非苹果风格…有一个想法?

Swift 2.0版本:

 //Declared at top of view controller var 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 this let 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 controller var 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 this let 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 func donePressed() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } 

UIToolBar文档

'inputAccessoryView'文档