如何在iOS中为numpad键盘添加"完成"按钮

Geo*_*bin 83 iphone cocoa-touch uitextfield uikit ios

因此,numpad键盘默认没有"完成"或"下一步"按钮,所以我想添加一个.在iOS 6及更低版本中,有一些技巧可以在键盘上添加一个按钮,但它们似乎不适用于iOS 7.

首先,我订阅显示通知的键盘

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

然后我尝试在键盘出现时添加一个按钮:

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)

但for循环不会运行,因为它找不到任何子视图.有什么建议?我找不到iOS7的任何解决方案,所以有不同的方式我应该这样做吗?

编辑:感谢工具栏人员的所有建议,但我宁愿不去那条路,因为我的空间很差(而且有点难看).

Bha*_*vin 185

在更安全的方法是使用一个UIToolBar带有Done按钮inputAccessoryView.


示例代码:

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;
Run Code Online (Sandbox Code Playgroud)

您的-doneClicked方法应如下所示:

- (IBAction)doneClicked:(id)sender
{
    NSLog(@"Done Clicked.");
    [self.view endEditing:YES];
}
Run Code Online (Sandbox Code Playgroud)

示例代码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
Run Code Online (Sandbox Code Playgroud)

您的-doneClicked方法应如下所示:

func doneClicked(sender: AnyObject) {
  self.view.endEditing(true)
}
Run Code Online (Sandbox Code Playgroud)

  • @GeorgeMcKibbin:这里的空间不应该是问题,因为它只会在您输入时占用该空间.另外,根据我的说法,这种方法比通常Apple不喜欢的键盘要好得多. (3认同)

And*_*eev 129

更简单的方法:

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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

目标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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我已经创建了一个名为DCKit的有用库,它已经有了开箱即用的工具栏:

iOS中键盘上方的完成工具栏(使用DCKit库)

它还有许多其他很酷的功能.

  • 不,我不这么认为.注释不应该用于编写代码:) (4认同)
  • 这应该作为改进(评论)添加到以前正确的答案IMO或期望下来投票.新答案应该涉及对原始问题的不同方法,而不是对现有问题的改进.尽管如此,谢谢你的改进.;-) (3认同)
  • 是的,我不使用`initWithTitle:@"完成"`,我使用`initWithBarButtonSystemItem:UIBarButtonSystemItemDone`代替.这将返回标准Apple的Done bar按钮.而且,它已经本地化了 (2认同)

Bal*_*ari 27

这是在iOS7数字键盘中投影完成按钮的简单方法.在UITextField的下面委托方法中,添加键盘显示的通知.

-(void)textFieldDidBeginEditing:(UITextField *)textField {

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];
}
Run Code Online (Sandbox Code Playgroud)

现在实现如下方法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];
        }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

现在将此宏添加到合适的标头以检测SYSTEM_VERSION

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

  • 在iOS8这个完成按钮没有隐藏,解雇后的键盘. (7认同)
  • 这个答案虽然很聪明,但肯定会破裂. (2认同)

Nyc*_*cen 13

因为我必须翻译它,所以只使用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)
    }
Run Code Online (Sandbox Code Playgroud)