(转发)InputAccessoryView的使用方法

转自:http://blog.sina.com.cn/s/blog_45e2b66c01015we9.html

UITextFields and UITextViews have an inputAccessoryView property, which you can set to any view, that is automatically displayed above and animated with the keyboard.

Note that the view you use should neither be in the view hierarchy elsewhere, nor should you add it to some superview, this is done for you.

翻译:
UITextFields和UITextView有一个inputAccessoryView的属性,当你想在键盘上展示一个自定义的view时,你就可以设置该属性。你设置的view就会自动和键盘keyboard一起显示了。

需要注意的是,你所自定义的view既不应该处在其他的视图层里,也不应该成为其他视图的子视图。其实也就是说,你所自定义的view只需要赋给属性inputAccessoryView就可以了,不要再做其他多余的操作。

我们在使用UITextView和UITextField的时候,可以通过它们的inputAccessoryView属性给输入时呼出的键盘加一个附属视图,通常是UIToolBar,用于回收键盘。

代码如下:

//定义一个toolBar
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];

//设置style
[topView setBarStyle:UIBarStyleBlack];

//定义两个flexibleSpace的button,放在toolBar上,这样完成按钮就会在最右边
UIBarButtonItem * button1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];

UIBarButtonItem * button2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];

//定义完成按钮
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];

//在toolBar上加上这些按钮
NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
[topView setItems:buttonsArray];
// [textView setInputView:topView];
[textView setInputAccessoryView:topView];


//隐藏键盘
-(void)resignKeyboard
{
[textView resignFirstResponder];
}

注意:

       inputView就是显示键盘的view,如果重写这个view则不再弹出键盘,而是弹出自己的view.如果想实现当某一控件变为第一响应者时不弹出 键盘而是弹出我们自定义的界面,那么我们就可以通过修改这个inputView来实现,比如弹出一个日期拾取器。

        inputView不会随着键盘出现而出现,设置了InputView只会当UITextField或者UITextView变为第一相应者时显示出来, 不会显示键盘了。设置了InputAccessoryView,它会随着键盘一起出现并且会显示在键盘的顶端。InutAccessoryView默认为 nil.

原文地址:https://www.cnblogs.com/MengXY/p/4161810.html