如何在 iOS 的小键盘键盘上添加“完成”按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20192303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a 'Done' button to numpad keyboard in iOS
提问by George McKibbin
So, the numpad keyboard doesn't come with a 'Done' or 'Next' button by default so I'd like to add one. In iOS 6 and below there were some tricks to add a button to the keyboard but they don't seem to be working in iOS 7.
因此,小键盘键盘默认没有“完成”或“下一步”按钮,所以我想添加一个。在 iOS 6 及更低版本中,有一些向键盘添加按钮的技巧,但它们似乎不适用于 iOS 7。
First I subscribe to the keyboard showing notification
首先我订阅了显示通知的键盘
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
Then I try to add a button when the keyboard shows up:
然后我尝试在键盘出现时添加一个按钮:
- (void)keyboardWillShow:(NSNotification *)note
{
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeSystem];
doneButton.frame = CGRectMake(0, 50, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(dismissKeyboard) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++)
{
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
But the for loop doesn't run because it doesn't find any subviews. Any suggestions? I couldn't find any solutions for iOS7 so is there a different way I'm supposed to be doing this?
但是 for 循环没有运行,因为它没有找到任何子视图。有什么建议?我找不到适用于 iOS7 的任何解决方案,所以我应该以不同的方式来做这件事吗?
Edit: Thanks for all the suggestions for toolbars guys but I'd rather not go down that route as I'm quite space poor (and it is kind of ugly).
编辑:感谢对工具栏家伙的所有建议,但我宁愿不走那条路,因为我空间不足(而且有点难看)。
采纳答案by Balram Tiwari
This is a simple way of projecting a done button in iOS7 num-keypad. In the below delegate method of UITextField, add a notification for keyboard show.
这是在 iOS7 num-keypad 中投影完成按钮的简单方法。在下面 UITextField 的委托方法中,添加键盘显示的通知。
-(void)textFieldDidBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
Now implement the method keyboardWillShow
as below. Here we need to take extra care for iOS7.
现在实现如下方法keyboardWillShow
。这里我们需要特别注意iOS7。
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:@"doneButtonNormal.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"doneButtonPressed.png"] forState:UIControlStateHighlighted];
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
dispatch_async(dispatch_get_main_queue(), ^{
UIView *keyboardView = [[[[[UIApplication sharedApplication] windows] lastObject] subviews] firstObject];
[doneButton setFrame:CGRectMake(0, keyboardView.frame.size.height - 53, 106, 53)];
[keyboardView addSubview:doneButton];
[keyboardView bringSubviewToFront:doneButton];
[UIView animateWithDuration:[[note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]-.02
delay:.0
options:[[note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]
animations:^{
self.view.frame = CGRectOffset(self.view.frame, 0, 0);
} completion:nil];
});
}else {
// locate keyboard view
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
});
}
}
Now add this macro to suitable header to detect the SYSTEM_VERSION
现在将此宏添加到合适的标头以检测 SYSTEM_VERSION
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
回答by Bhavin
The much safer approach is to use a UIToolBar
with Done
Button as inputAccessoryView
.
更安全的方法是使用UIToolBar
with Done
Button as inputAccessoryView
。
Sample Code :
示例代码:
UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;
Your -doneClicked
method should look like this :
你的-doneClicked
方法应该是这样的:
- (IBAction)doneClicked:(id)sender
{
NSLog(@"Done Clicked.");
[self.view endEditing:YES];
}
Sample Code Swift:
示例代码 Swift:
let keyboardDoneButtonView = UIToolbar.init()
keyboardDoneButtonView.sizeToFit()
let doneButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self,
action: Selector("doneClicked:")))
keyboardDoneButtonView.items = [doneButton]
textFieldInput.inputAccessoryView = keyboardDoneButtonView
Your -doneClicked
method should look like this :
你的-doneClicked
方法应该是这样的:
func doneClicked(sender: AnyObject) {
self.view.endEditing(true)
}
回答by Andrey Gordeev
Even easier way:
更简单的方法:
Swift 3.0 and above:
Swift 3.0 及以上:
func addDoneButton() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done,
target: view, action: #selector(UIView.endEditing(_:)))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
Swift 2.3 and below:
Swift 2.3 及以下:
func addDoneButton() {
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace,
target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .Done,
target: view, action: #selector(UIView.endEditing(_:)))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
Objective C:
目标C:
- (void)addDoneButton {
UIToolbar* keyboardToolbar = [[UIToolbar alloc] init];
[keyboardToolbar sizeToFit];
UIBarButtonItem *flexBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self.view action:@selector(endEditing:)];
keyboardToolbar.items = @[flexBarButton, doneBarButton];
self.textField.inputAccessoryView = keyboardToolbar;
}
EDIT:
编辑:
I've created a useful library called DCKit, which already have the toolbar out of the box:
我创建了一个名为DCKit的有用库,它已经具有开箱即用的工具栏:
It also has many other cool features.
它还具有许多其他很酷的功能。
回答by Nycen
Just building on answers above with the Swift version since I had to translate it:
因为我不得不翻译它,所以只是基于上面的 Swift 版本的答案:
@IBOutlet weak var numberTextField: UITextField!
override func viewDidLoad() {
addDoneButtonTo(numberTextField)
}
// MARK: Done for numberTextField
private func addDoneButtonTo(textField: UITextField) {
let flexBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "didTapDone:")
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
}
func didTapDone(sender: AnyObject?) {
numberTextField.endEditing(true)
}
回答by Himanshu Gupta
You can use
您可以使用
myTextField.inputAccessoryView =_inputView;
myTextField.inputAccessoryView =_inputView;
input accessory view is a view that comes over the keyboard always and dismiss with the [textfield resignFirstResponder]
输入附件视图是一个总是出现在键盘上并用 [textfield resignFirstResponder]
put doneover the input view and perform resignfirst responder of the textfields.
放置done输入视图并执行文本字段的 resignfirst responder。
回答by alvarodoune
Just use
只需使用
yourTextField.inputAccessoryView
yourTextField.inputAccessoryView
hope you help
希望你有所帮助
回答by loloa
enter code here
1. register the controller to the notification
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Keyboard events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
2. don't forget to remove the controller from the notification centre
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.view endEditing:YES];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
3. implement keyboard notification handlers
- (void)keyboardWillShow:(NSNotification *)notification {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 107, 106, 53);
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(doneButton:)forControlEvents:UIControlEventTouchUpInside];
// save the reference to the button in order to use it in keyboardWillHide method
self.donekeyBoardBtn = doneButton;
// to my mind no need to search for subviews
UIWindow *windowContainigKeyboard = [[[UIApplication sharedApplication] windows] lastObject];
[windowContainigKeyboard addSubview:self.donekeyBoardBtn];
self.donekeyBoardBtn.frame = CGRectMake(0., CGRectGetHeight(w.frame) - CGRectGetHeight(self.donekeyBoardBtn.frame), CGRectGetWidth(self.donekeyBoardBtn.frame), CGRectGetHeight(self.donekeyBoardBtn.frame));
}
- (void)keyboardWillHide:(NSNotification *)notification {
[self.donekeyBoardBtn removeFromSuperview];
}
4. implement done button action
- (void)doneButton:(id)sender{
// add needed implementation
[self.view endEditing:YES];
}
回答by user3288300
You do need to detect whether you are on a phone or iPad since the iPad implements a return key on the "number" pad
您确实需要检测您使用的是手机还是 iPad,因为 iPad 在“数字”键盘上实现了返回键
回答by anarchist
Keyboard view could be found hasPrefix:@"UIKeyboard", the button can not be added as a subview. Here's my solution: enter link description here
键盘视图可以找到hasPrefix:@"UIKeyboard",按钮不能作为子视图添加。这是我的解决方案:在此处输入链接描述