¿Cómo puedo detectar cuándo se muestra y oculta el teclado de mi aplicación?Cómo detectar cuándo se muestra y oculta el teclado
Respuesta
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
}
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.
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
Usted podría utilizar KBKeyboardObserver biblioteca. Contiene algunos ejemplos y proporciona una interfaz simple.
y semi-operativo –
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)
}
Si quita su observador en vista WillDisappear ... debería agregarlo a la vista Mostrar en lugar de viewDidLoad. – FouZ
Eso es cierto, no dude en editar la respuesta. Lo aceptaré – Esqarrouth
@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
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
}
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.
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)
}
El '+ =' aparece para hacer que las inserciones sean cada vez más grandes. – Wez
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)
}
- 1. iOS evento cuando el teclado se oculta
- 2. teclado en UIWebView muestra y luego se oculta en el foco de entrada
- 3. iPhone - El teclado oculta TextField
- 4. Teclado oculta TabBar
- 5. UIVIew endEditing: YES no oculta el teclado
- 6. IE 7 muestra oculta y no muestra ninguno Elementos
- 7. ¿Cómo se muestra el teclado virtual de un servicio?
- 8. ¿Cómo se muestra el teclado de forma predeterminada en UITextView?
- 9. ¿Cómo se muestra el teclado numérico en EditText en android?
- 10. Cómo detectar cuándo se usan history.pushState y history.replaceState?
- 11. UIPopoverView se distorsiona cuando se muestra el teclado + iPad
- 12. Android: Detectar inactividad del usuario/Detectar (teclado) entrada de teclado
- 13. ¿Cómo detectar cuándo se cambia el tema en WP7?
- 14. ¿Cómo detectar cuándo se está maximizando el formulario?
- 15. Compra InApp - Cómo detectar cuándo se muestra Alert 'Confirmar su compra en la aplicación'
- 16. ¿Cómo se muestra u oculta el valor de entrada en el enfoque?
- 17. Averigüe cuándo se cambió el diseño del teclado
- 18. Detectar si y cuándo se realizan llamadas jQuery AJAX
- 19. detectar el botón de búsqueda del teclado
- 20. Sphinx, reStructuredText muestra/oculta fragmentos de código
- 21. ¿Cómo se muestra u oculta el icono del sobre de Outlook?
- 22. jQuery: fadeToggle() muestra/oculta el texto del enlace no cambia
- 23. detectar el diseño del teclado con javascript
- 24. ¿Cómo detectar cuándo se inicia la reproducción de VideoView (Android)?
- 25. ¿Cómo puedo detectar cuándo se carga una página web?
- 26. ¿Cómo puedo detectar cuándo se ha movido mi Vista?
- 27. ¿Cómo puedo detectar cuándo se está redireccionando la salida?
- 28. Cómo mantener el tamaño de la imagen de fondo cuando se muestra el teclado del software
- 29. android: Cómo evitar el cambio de tamaño de la ventana cuando se muestra el teclado virtual
- 30. ¿Cómo puedo eliminar el teclado suave de muestra de Android?
¿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? –
@apprentice ¿Quiere decir que el teclado no aparece si tabula? –
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 –