Created
November 22, 2019 19:23
-
-
Save fitomad/c2fbe5ea55eed9991868c51fb6c6f69c to your computer and use it in GitHub Desktop.
Manage iOS keyboard presentation and dismiss with your SwiftUI views.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// KeyboardResponder.swift | |
// MoveMAD | |
// | |
// Created by Adolfo Vera Blasco on 19/11/2019. | |
// Copyright © 2019 desappstre {eStudio}. All rights reserved. | |
// | |
import SwiftUI | |
public final class KeyboardResponder: ObservableObject | |
{ | |
/// Altura del teclado en un momento dado | |
@Published public private(set) var currentHeight: CGFloat = 0.0 | |
/// Duración de la animación del sistema que presenta el teclado | |
@Published public private(set) var animationDuration: Double = 0.0 | |
/** | |
Nos *enganchamos* a las notificaciones | |
de presentación del teclado. | |
*/ | |
public init() | |
{ | |
NotificationCenter.default.addObserver(self, | |
selector: #selector(keyboardWillShow(notification:)), | |
name: UIResponder.keyboardWillShowNotification, | |
object: nil) | |
NotificationCenter.default.addObserver(self, | |
selector: #selector(keyboardWillHide(notification:)), | |
name: UIResponder.keyboardWillHideNotification, | |
object: nil) | |
} | |
/** | |
Una vez terminada la vida de este objeto | |
dejamos de estar atentos a las notificaciones | |
*/ | |
deinit | |
{ | |
NotificationCenter.default.removeObserver(self) | |
} | |
/** | |
Cuando el sistema nos notifica que se va a | |
**presentar** el teclado recuperamos dos valores: | |
1. El tamaño del `frame` que va a ocupar el teclado | |
2. El tiempo que se va a emplear en animar la presentación | |
*/ | |
@objc func keyboardWillShow(notification: Notification) -> Void | |
{ | |
guard let userInfo = notification.userInfo, | |
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue, | |
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double | |
else | |
{ | |
return | |
} | |
self.animationDuration = animationDuration | |
self.currentHeight = keyboardFrame.cgRectValue.height | |
} | |
/** | |
Cuando el sistema nos notifica que se va a | |
**ocultar** el teclado un único valor, ya que el | |
tamaño del teclado será de 0 | |
1. El tiempo que se va a emplear en animar la presentación | |
*/ | |
@objc func keyboardWillHide(notification: Notification) | |
{ | |
guard let userInfo = notification.userInfo, | |
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double | |
else | |
{ | |
return | |
} | |
self.animationDuration = animationDuration | |
self.currentHeight = 0.0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment