2010-12-07 5 views

Répondre

144

Dans la méthode viewDidLoad de votre classe mis en place pour écouter les messages sur le clavier:

// Listen for keyboard appearances and disappearances 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidShow:) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidHide:) 
              name:UIKeyboardDidHideNotification 
              object:nil]; 

Puis, dans les méthodes que vous spécifiez (dans ce cas keyboardDidShow et keyboardDidHide) vous pouvez faire quelque chose à ce sujet:

- (void)keyboardDidShow: (NSNotification *) notif{ 
    // Do something here 
} 

- (void)keyboardDidHide: (NSNotification *) notif{ 
    // Do something here 
} 
+0

Est-ce que ne fonctionne pas si vous tabulez à travers les champs. Je me demande quelle serait la solution pour cela et si vous pouvez même tabuler sur un iPad réel? –

+0

@apprentice Voulez-vous dire que le clavier ne s'affiche pas si vous tabulez? –

+0

S'il y a des champs encore couverts par le clavier en dessous de celui avec le focus, la vue restera sur l'onglet parce que la notification est envoyée seulement au moment où le clavier glisse –

3

Consultez la section Managing the Keyboard du «Guide de programmation du texte, du Web et de l'édition» pour plus d'informations sur le suivi du clavier affiché ou masqué et sur la manière de l'afficher/de le supprimer manuellement.

3

Vous voulez vous inscrire aux deux notifications de clavier:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name: UIKeyboardDidShowNotification object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) name: UIKeyboardDidHideNotification object:nil]; 

après Grand sur la façon d'ajuster votre TextField au clavier - http://iosdevelopertips.com/user-interface/adjust-textfield-hidden-by-keyboard.html

0

Vous pouvez utiliser la bibliothèque KBKeyboardObserver. Il contient quelques exemples et fournit une interface simple.

+0

et semi-ouvrable –

62

Swift 4:

override func viewWillAppear(_ animated: Bool) {   
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: Notification.Name.UIKeyboardWillShow, object: nil) 
} 

@objc func keyboardWillAppear() { 
    //Do something here 
} 

@objc func keyboardWillDisappear() { 
    //Do something here 
} 

override func viewWillDisappear(_ animated: Bool) { 
    NotificationCenter.default.removeObserver(self) 
} 

Swift:

override func viewDidLoad() { 
    super.viewDidLoad() 

    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil) 
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil) 
} 

func keyboardWillAppear(notification: NSNotification){ 
    // Do something here 
} 

func keyboardWillDisappear(notification: NSNotification){ 
    // Do something here 
} 

Edit:
Vous pouvez ajouter ce morceau de code aussi. Cela empêche les plantages rares qui se produisent lorsque vous modifiez votre vue.

override func viewWillDisappear(animated: Bool) { 
    super.viewWillDisappear(animated) 
    NSNotificationCenter.defaultCenter().removeObserver(self) 
} 
+7

Si vous supprimez votre observateur sur viewWillDisappear ... vous devez l'ajouter dans viewWillAppear au lieu de viewDidLoad. – FouZ

+0

C'est vrai, n'hésitez pas à modifier la réponse. Je vais l'accepter – Esqarrouth

+0

@FouZ vaut-il mieux supprimer les observateurs de 'deinit' comme ceci:' deinit { NSNotificationCenter.defaultCenter(). RemoveObserver (self, nom: UIKeyboardWillShowNotification, objet: nil) NSNotificationCenter.defaultCenter(). removeObserver (auto, nom: UIKeyboardWillHideNotification, objet: néant) } ' – Crashalot

17

Swift 3:

NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 

func keyboardWillShow(_ notification: NSNotification){ 
    // Do something here 
} 

func keyboardWillHide(_ notification: NSNotification){ 
    // Do something here 
} 
1

Si vous avez plus d'un UITextField s et vous devez faire quelque chose quand (ou avant) clavier apparaît ou disparaît, vous pouvez mettre en œuvre cette approche.

Ajoutez UITextFieldDelegate à votre cours. Assigner compteur entier, disons:

NSInteger editCounter; 

Set ce compteur à zéro quelque part dans viewDidLoad. Ensuite, implémentez textFieldShouldBeginEditing et textFieldShouldEndEditing les méthodes de délégué.

Dans le premier, ajoutez 1 à editCounter. Si la valeur de editCounter devient 1 - cela signifie que le clavier apparaîtra (au cas où vous retourneriez YES). Si editCounter> 1 - cela signifie que le clavier est déjà visible et qu'un autre UITextField détient le focus.

Sous textFieldShouldEndEditing soustrayez 1 de editCounter. Si vous obtenez zéro - le clavier sera rejeté, sinon il restera à l'écran.

2

Swift 4:

NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillShow(_:)), 
    name: Notification.Name.UIKeyboardWillShow, 
    object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)), 
    name: Notification.Name.UIKeyboardWillHide, 
    object: nil) 

Ensuite, la méthode ajoutant pour arrêter l'écoute des notifications quand se termine la vie de l'objet: -

Then add the promised methods from above to the view controller: 
deinit { 
    NotificationCenter.default.removeObserver(self) 
} 
func adjustKeyboardShow(_ open: Bool, notification: Notification) { 
    let userInfo = notification.userInfo ?? [:] 
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue 
    let height = (keyboardFrame.height + 20) * (open ? 1 : -1) 
    scrollView.contentInset.bottom += height 
    scrollView.scrollIndicatorInsets.bottom += height 
} 

@objc func keyboardWillShow(_ notification: Notification) { 
    adjustKeyboardShow(true, notification: notification) 
} 
@objc func keyboardWillHide(_ notification: Notification) { 
    adjustKeyboardShow(false, notification: notification) 
} 
+0

Le '+ =' apparaît pour rendre les insets de plus en plus gros. – Wez

0

Swift 4 - dd 20 october 2017

override func viewDidLoad() { 
    [..] 

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil) 
} 

@objc func keyboardWillAppear(_ notification: NSNotification) { 
    if let userInfo = notification.userInfo, 
     let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue).cgRectValue { 
      let inset = keyboardFrame.height // if scrollView is not aligned to bottom of screen, subtract offset 
      scrollView.contentInset.bottom = inset 
      scrollView.scrollIndicatorInsets.bottom = inset 
    } 
} 

@objc func keyboardWillDisappear(_ notification: NSNotification) { 
    scrollView.contentInset.bottom = 0 
    scrollView.scrollIndicatorInsets.bottom = 0 
} 

deinit { 
    NotificationCenter.default.removeObserver(self) 
} 
Questions connexes