苹果应用中,编辑TextField、TextView时弹出来的键盘有时候很闹心,不知如何隐藏。本文简单实现了带“隐藏”按钮的工具栏,用户可以随时隐藏键盘。
先上图
代码实现
首先,定义一个工具栏变量;
UIToolbar *tbHide; // toolbar for keyboard hiding
接下来,创建并设置工具栏;
// create keyboard toolbar, has two buttons
tbHide = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 36)];
[tbHide setBarStyle:UIBarStyleBlack];
// "Hide" button
UIBarButtonItem * hideButton = [[UIBarButtonItem alloc]initWithTitle:@"Hide" style:UIBarButtonItemStyleBordered target:self action:@selector(hideKeyboard)];
// "Done" button
UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(hideKeyboard)];
NSArray * buttonsArray = [NSArray arrayWithObjects:hideButton,btnSpace,doneButton,nil];
[tbHide setItems:buttonsArray];
// set thoes controls that need hide keyboard functions
[self.textField setInputAccessoryView:tbHide];
[self.textView setInputAccessoryView:tbHide];
最后,实现隐藏键盘功能。
// hide keyboard
- (void)hideKeyboard
{
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}
以上就是隐藏键盘功能的实现部分,比较简单。
下面给出工程源码,供大家下载!