Mostrar y ocultar teclado desplazando la view
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
//MARK: Keyboard
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
if (deviceIdiom != .pad) {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= (keyboardSize.height - 60)
}
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
if (deviceIdiom != .pad) {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += (keyboardSize.height - 60)
}
}
}
}
0) La view de pantalla debe tener una view dentro que es la que se desplazará
0.5) El ViewController debe heredar de TextViewController (clase propia) en .h
@interface LOCreateAccountViewController : TextViewController
1) Crear una constraint a bottom y top (con distancia 0) entre la view nueva y la propia de la pantalla
2) Enlazarla en el .m (dentro de interface)
3) Controlar el campo RETURN KEY de los TextFields
4) Añadir el código:
-(void)keyboardWillShow:(NSNotification *)notification{
NSDictionary *info = [notification userInfo];
NSValue *kbFrame = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrame = [kbFrame CGRectValue];
CGRect finalKeyboardFrame = [self.view convertRect:keyboardFrame fromView:self.view.window];
int kbHeight = finalKeyboardFrame.size.height;
int height = kbHeight;
int offsetY = self.currentField.frame.origin.y+ (int) self.currentField.frame.size.height;
int vHeight = self.view.frame.size.height;
if(vHeight - offsetY < height){
self.cBottom.constant = abs(vHeight - height - offsetY - 10);
self.cContentTop.constant = 20-self.cBottom.constant;
}
}
-(void)keyboardWillHide:(NSNotification *)notification{
[super keyboardWillHide:notification];
self.cContentBottom.constant = 0;
self.cContentTop.constant = 20;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([textField isEqual:self.textFieldEmail]) {
[textField resignFirstResponder];
[self.textFieldPassword becomeFirstResponder];
}
if ([textField isEqual:self.textFieldPassword]) {
[textField resignFirstResponder];
}
return YES;
}