Skip to content

Instantly share code, notes, and snippets.

@Pircate
Last active October 21, 2020 13:50
Show Gist options
  • Save Pircate/de34cca4143f323aa22ef6b19111b3e7 to your computer and use it in GitHub Desktop.
Save Pircate/de34cca4143f323aa22ef6b19111b3e7 to your computer and use it in GitHub Desktop.
extension UITextInput where Self: UIView {
func avoidCoveredByKeyboard(
from view: UIView,
_ offset: CGFloat = 0
) {
NotificationCenter.default.addObserver(
forName: UIApplication.keyboardWillShowNotification,
object: nil,
queue: .main
) { [weak self] note in
guard let self = self, self.isFirstResponder else { return }
let keyboardHeight: CGFloat
if let keyboardFrame = note.userInfo?[UIApplication.keyboardFrameEndUserInfoKey]
as? CGRect {
keyboardHeight = keyboardFrame.height
} else {
keyboardHeight = 0
}
UIView.beginAnimations("ResizeForShowKeyboard", context: nil)
UIView.setAnimationCurve(self.keyboardAnimationCurve(from: note.userInfo))
UIView.setAnimationDuration(self.keyboardAnimationDuration(from: note.userInfo))
view.transform = CGAffineTransform(translationX: 0, y: -(keyboardHeight + offset))
UIView.commitAnimations()
}
NotificationCenter.default.addObserver(
forName: UIApplication.keyboardWillHideNotification,
object: nil,
queue: .main
) { [weak self] note in
guard let self = self, self.isFirstResponder else { return }
UIView.beginAnimations("ResizeForHideKeyboard", context: nil)
UIView.setAnimationCurve(self.keyboardAnimationCurve(from: note.userInfo))
UIView.setAnimationDuration(self.keyboardAnimationDuration(from: note.userInfo))
view.transform = CGAffineTransform.identity
UIView.commitAnimations()
}
}
private func keyboardAnimationCurve(from userInfo: [AnyHashable: Any]?) -> UIView.AnimationCurve {
guard let index = userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? Int else {
return .linear
}
if index >= 0, index <= 3 {
return .linear
} else {
return UIView.AnimationCurve.init(rawValue: index) ?? .linear
}
}
private func keyboardAnimationDuration(from userInfo: [AnyHashable: Any]?) -> TimeInterval {
return userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment