我正在制作一个通用应用程序,其中包含一个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];
希望这可以帮到你
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 View的键盘。
只是提供这个信息。
// Para esconder el teclado al oprimir el fondo de la pantalla
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.answerTextView endEditing:YES];
}
从theapplady中提取
doneWithNumberPad:
方法来在文本字段上真正取消第一响应者。 - rmaddy[doneToolbar setTintColour:[UIColor whiteColor]];
即可。 - kinadian