Comment append un button «Terminé» au keyboard du pavé numérique dans iOS

Donc, le keyboard du pavé numérique ne vient pas avec un button 'Terminé' ou 'Suivant' par défaut donc je voudrais en append un. Dans iOS 6 et ci-dessous, il y avait quelques astuces pour append un button au keyboard, mais ils ne semblent pas fonctionner sous iOS 7.

Je suis d'abord abonné au keyboard affichant la notification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 

Ensuite, j'essaie d'append un button lorsque le keyboard apparaît:

 - (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]; } } 

Mais la boucle for ne s'exécute pas car elle ne trouve aucune sous-vue. Aucune suggestion? Je n'ai pas trouvé de solution pour iOS7, alors y a-t-il une autre façon de le faire?

Edit: Merci pour toutes les suggestions pour les barres d'outils mais je préfère ne pas descendre cette route car je suis assez pauvre en espace (et c'est plutôt moche).

C'est un moyen simple de projeter un button terminé dans le pavé numérique iOS7. Dans la méthode délégate ci-dessous de UITextField, ajoutez une notification pour l'affichage du keyboard.

 -(void)textFieldDidBeginEditing:(UITextField *)textField { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; } 

Maintenant, implémentez la méthode keyboardWillShow comme ci-dessous. Ici, nous devons prendre des précautions supplémentaires pour 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]; } }); } } 

Maintenant, ajoutez cette macro à l'en-tête approprié pour détecter la SYSTEM_VERSION

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

L'approche la plus sûre consiste à utiliser un UIToolBar avec le button Done tant que inputAccessoryView .


Exemple de 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; 

Votre méthode -doneClicked devrait ressembler à ceci:

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

Exemple de code 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 

Votre méthode -doneClicked devrait ressembler à ceci:

 func doneClicked(sender: AnyObject) { self.view.endEditing(true) } 

Encore plus simple:

Swift 3.0 et supérieur :

 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 et ci-dessous :

 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 } 

Objectif 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; } 

MODIFIER:

J'ai créé une bibliothèque utile appelée DCKit , qui a déjà la barre d'outils prête à l'emploi :

Terminer la barre d'outils au-dessus du clavier dans iOS (avec la bibliothèque DCKit)

Il a également beaucoup d'autres fonctionnalités intéressantes.

Je construisais juste les réponses ci-dessus avec la version Swift puisque je devais la traduire:

  @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) } 

Vous pouvez utiliser

myTextField.inputAccessoryView = _inputView;

La vue accessoire d'input est une vue qui vient toujours sur le keyboard et rejeter avec le [textfield resignFirstResponder]

mettre sur la vue d'input et effectuer le premier répondeur des champs de text.

Juste utiliser

yourTextField.inputAccessoryView

espère que tu aideras

 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]; } 

Voici un exemple d'affichage des buttons avec barre d'outils avec keyboard.

Vous avez besoin de détecter si vous êtes sur un téléphone ou un iPad car l'iPad implémente une touche de return sur le pavé numérique

La vue du keyboard peut être trouvé hasPrefix: @ "UIKeyboard", le button ne peut pas être ajouté comme sous-vue. Voici ma solution: entrez la description du lien ici