[英]Add a done button to the top of the keyboard
我正在制作一个具有UITextView的通用应用程序。 当应用程序在iPad上运行时,右下角有一个按钮,可以让我关闭键盘。 iPhone版没有这样的按钮。 我在一些iPhone应用程序上看到键盘顶部有一个带有完成选项的栏。 是否有一种简单的方法可以将iPad风格的键盘按钮添加到iPhone应用程序中。 如果没有,将完成样式栏添加到键盘顶部的最佳方法是什么? 提前致谢。
请试试这段代码
//set up a placeholder variable for the textfield user typing
UITextView *currentTextView;
-(void)addDoneToolBarToKeyboard:(UITextView *)textView
{
UIToolbar* doneToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
doneToolbar.barStyle = UIBarStyleBlackTranslucent;
doneToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonClickedDismissKeyboard)],
nil];
[doneToolbar sizeToFit];
textView.inputAccessoryView = doneToolbar;
}
//remember to set your text view delegate
//but if you only have 1 text view in your view controller
//you can simply change currentTextField to the name of your text view
//and ignore this textViewDidBeginEditing delegate method
- (void)textViewDidBeginEditing:(UITextView *)textView
{
currentTextView = textView;
}
-(void)doneButtonClickedDismissKeyboard
{
[currentTextView resignFirstResponder];
}
并在你的视图中添加这个加载
[self addDoneToolBarToKeyboard:self.textView];
希望有所帮助
同样的答案swift3 :
func addDoneToolBarToKeyboard(textView:UITextView)
{
let doneToolbar : UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50))
doneToolbar.barStyle = UIBarStyle.default
let flexibelSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let hideKeyboardItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.dismissKeyboard))
doneToolbar.items = [flexibelSpaceItem, hideKeyboardItem!]
doneToolbar.sizeToFit()
textView.inputAccessoryView = doneToolbar
}
和解雇功能将是:
func dismissKeyboard()
{
self.view.endEditing(true)
}
您可以通过以下方式随时在一行代码中执行此操作:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
to:nil
from:nil
forEvent:nil];
这会将resignFirstResponder
发送到响应者链。 当前文本视图将是第一个响应者,因此它将获取消息并辞职第一响应者。
我知道这是一个太迟的答案,但在iOS 8中我没有隐藏键盘,我的TEXT视图与答案之前。
仅供参考我只是添加这个。
// Para esconder el teclado al oprimir el fondo de la pantalla
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.answerTextView endEditing:YES];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.