添加按钮以隐藏键盘

问题描述

| 在用于隐藏键盘的UITextView上,有以下方法
...
    textfield.returnKeyType = UIReturnKeyDone;
    textfield.delegate = self;
....

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;

}
但是,如果我想将按钮“完成”留在“返回”上并添加一个按钮来隐藏键盘,我该怎么办?     

解决方法

        您可以为工具栏分配一个按钮,该按钮可取消键盘作为文本字段的
inputAccessoryView
。一个简单的例子是
UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:@selector(resignFirstResponder)] autorelease];
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0,320,44)] autorelease];
toolbar.items = [NSArray arrayWithObject:barButton];

textField.inputAccessoryView = toolbar;
    ,        Swift 2.0版本:
//Declared at top of view controller
var accessoryDoneButton: UIBarButtonItem!
let accessoryToolBar = UIToolbar(frame: CGRectMake(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
斯威夫特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,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 \'文档     ,        这可以更轻松地完成! 我在IB中的viewController.h中创建了一个自定义视图,我刚做了一个
IBOutlet UIView *accessoryView;
,将它们和一个
- (IBAction)dismissKeyboard;
相连 我在视图中放入了一个带有完成按钮的工具栏,并与IBAction建立了连接:
[textView resignFirstResponder]
- (void)viewDidLoad
{
    textView.inputAccessoryView = accessoryView;
    [super viewDidLoad];
}
但是实际上,这看起来有点奇怪且非苹果风格……有想法吗?