2010-12-07 11 views

Respuesta

144

En el método de la clase viewDidLoad establecido para escuchar mensajes sobre el teclado:

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

Luego, en los métodos que especifique (en este caso keyboardDidShow y keyboardDidHide) se puede hacer algo al respecto:

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

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

¿El no funciona si tabula a través de los campos. ¿Te preguntas cuál sería la solución para ese problema y si puedes navegar por un iPad real? –

+0

@apprentice ¿Quiere decir que el teclado no aparece si tabula? –

+0

si hay campos cubiertos por el teclado debajo del que tiene el foco, la vista se mantendrá fija en la pestaña debido a que la notificación se envía solo en el momento en que el teclado se desliza –

3

Consulte la sección Managing the Keyboard de la "Guía de programación de texto, web y edición" para obtener información sobre el seguimiento del teclado que se muestra u oculta, y cómo mostrarlo/descartarlo manualmente.

3

Usted desea darse de alta para las notificaciones 2 para teclado:

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

gran post sobre cómo ajustar su campo de texto con el teclado - http://iosdevelopertips.com/user-interface/adjust-textfield-hidden-by-keyboard.html

0

Usted podría utilizar KBKeyboardObserver biblioteca. Contiene algunos ejemplos y proporciona una interfaz simple.

+0

y semi-operativo –

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 
} 

Editar:
Es posible que desee agregar este pedazo de código también. Esto evita bloqueos raros que suceden cuando está cambiando su vista.

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

Si quita su observador en vista WillDisappear ... debería agregarlo a la vista Mostrar en lugar de viewDidLoad. – FouZ

+0

Eso es cierto, no dude en editar la respuesta. Lo aceptaré – Esqarrouth

+0

@FouZ es mejor eliminar los observadores de 'deinit' como esto:' deinit { NSNotificationCenter.defaultCenter(). RemoveObserver (self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter(). removeObserver (self, nombre: UIKeyboardWillHideNotification, objeto: nil) } ' – 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 usted tiene más de uno UITextField s y hay que hacer algo cuando aparece o desaparece (o antes) de teclado, se puede poner en práctica este enfoque.

Agregue UITextFieldDelegate a su clase. Asignar contador de números enteros, digamos:

NSInteger editCounter; 

Conjunto este contador a cero en algún lugar de viewDidLoad. A continuación, implemente los métodos delegados textFieldShouldBeginEditing y textFieldShouldEndEditing.

En el primero, agregue 1 a editCounter. Si el valor de editCounter se convierte en 1, significa que aparecerá el teclado (en caso de que devuelva SÍ). Si editCounter> 1 - esto significa que el teclado ya está visible y otro UITextField mantiene el foco.

En textFieldShouldEndEditing resta 1 de editCounter. Si obtienes cero, el teclado se descartará, de lo contrario permanecerá en la pantalla.

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) 

A continuación, añadir el método para dejar de escuchar para notificaciones cuando termina la vida del objeto: -

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

El '+ =' aparece para hacer que las inserciones sean cada vez más grandes. – 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) 
} 
Cuestiones relacionadas