2012-08-16 14 views
31

¿Es posible obtener el marco, en realidad su altura, del teclado de forma dinámica? Como tengo un UITextView y me gustaría ajustar su altura de acuerdo con la altura del cuadro del teclado, cuando se cambia el método de entrada del teclado. Como sabe, los diferentes métodos de entrada pueden tener diferentes alturas de cuadro del teclado.Obtener el marco del teclado de forma dinámica

Respuesta

97

intente esto:

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

- (void)keyboardWasShown:(NSNotification *)notification 
{ 

// Get the size of the keyboard. 
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

//Given size may not account for screen rotation 
int height = MIN(keyboardSize.height,keyboardSize.width); 
int width = MAX(keyboardSize.height,keyboardSize.width); 

//your other code here.......... 
} 

Tutorial for more information

+1

Esto es particularmente útil cuando se trabaja con diferentes teclados de altura/tipo en iOS8. Hasta ahora, simplemente hardcoding 216 (retrato) haría el truco. Gracias. – n00bProgrammer

+2

en ios 8 todavía está returándose 216, lo cual es incorrecto. – harshitgupta

+0

@Hector ¿Funcionará también para iOS8? – msmq

8

Simplemente sigue este tutorial de Apple y obtendrás lo que quieras. Apple Documentation. Para determinar el área cubierta por el teclado, consulte este tutorial.

+0

Pero, ¿cómo podría detectar el método de entrada para cambiar la acción? –

+0

Si usted es el programador, entonces debe saber qué teclado de entrada ha abierto en cualquier momento. – doNotCheckMyBlog

+3

Desearía saberlo, pero no pude. Si sabe cómo detectar el método de entrada, cambie la acción y obtenga la altura del teclado actual, ¿podría informarme amablemente? Realmente lo aprecio :) –

2

Para los usuarios Swift 3, el código @Hector (con algunas adiciones) sería:

En su viewDidLoad añadir el observador:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil) 

A continuación, implemente los métodos:

func keyboardDidShow(_ notification: NSNotification) { 
    print("Keyboard will show!") 
    // print(notification.userInfo) 

    let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size 
    print("Keyboard size: \(keyboardSize)") 

    let height = min(keyboardSize.height, keyboardSize.width) 
    let width = max(keyboardSize.height, keyboardSize.width) 

} 

func keyboardDidHide(_ notification: NSNotification) { 
     print("Keyboard will hide!") 
} 
0

Puede agregar este código a la vista que contiene el campo de texto en Swift 3. Esto hará que el campo de texto se mueva hacia arriba y hacia abajo con el teclado.

private var keyboardIsVisible = false 
private var keyboardHeight: CGFloat = 0.0 

// MARK: Notifications 

private func registerForKeyboardNotifications() { 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
} 
private func deregisterFromKeyboardNotifications() { 
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
} 

// MARK: Triggered Functions 

@objc private func keyboardWillShow(notification: NSNotification) { 
    keyboardIsVisible = true 
    guard let userInfo = notification.userInfo else { 
     return 
    } 
    if let keyboardHeight = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height { 
     self.keyboardHeight = keyboardHeight 
    } 
    if !textField.isHidden { 
     if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, 
      let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { 
      animateHUDWith(duration: duration.doubleValue, 
          curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut, 
          toLocation: calculateTextFieldCenter()) 
     } 
    } 
} 

@objc private func keyboardWillBeHidden(notification: NSNotification) { 
    keyboardIsVisible = false 
    if !self.isHidden { 
     guard let userInfo = notification.userInfo else { 
      return 
     } 
     if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, 
      let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { 
      animateHUDWith(duration: duration.doubleValue, 
          curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut, 
          toLocation: calculateTextFieldCenter()) 
     } 
    } 
} 

// MARK: - Helpers 

private func animateHUDWith(duration: Double, curve: UIViewAnimationCurve, toLocation location: CGPoint) { 
    UIView.beginAnimations(nil, context: nil) 
    UIView.setAnimationDuration(TimeInterval(duration)) 
    UIView.setAnimationCurve(curve) 
    textField.center = location 
    UIView.commitAnimations() 
} 

private func calculateTextFieldCenter() -> CGPoint { 
    if !keyboardIsVisible { 
     return self.center 
    } else { 
     let yLocation = (self.view.frame.height - keyboardHeight)/2 
     return CGPoint(x: self.center.x, y: yLocation) 
    } 
} 
Cuestiones relacionadas