Skip to content

Instantly share code, notes, and snippets.

@gmoraleda
Created November 22, 2018 16:15
Show Gist options
  • Save gmoraleda/3071f5dd0335c0cf8b6cc205265046b6 to your computer and use it in GitHub Desktop.
Save gmoraleda/3071f5dd0335c0cf8b6cc205265046b6 to your computer and use it in GitHub Desktop.
// MARK: - Keyboard Insets
extension UIViewController {
internal func updateInsets(for event: KeyboardEvent, scrollView: UIScrollView?) {
guard let scrollView = scrollView else { return }
let newKeyboardFrame = event.keyboardFrameEnd
let duration = event.duration
let newKeyboardHeight = newKeyboardFrame.origin.y < UIScreen.main.bounds.height ? newKeyboardFrame.height : Sizes.zero
updateInsets(duration: duration, keyboardHeight: newKeyboardHeight, scrollView: scrollView)
}
private func updateInsets(duration: TimeInterval? = nil, keyboardHeight: CGFloat = Sizes.zero, scrollView: UIScrollView) {
let bottomInset: CGFloat
let insets: UIEdgeInsets
bottomInset = keyboardHeight > 0.0 ? keyboardHeight - view.safeAreaInsets.bottom : Sizes.zero
insets = scrollView.contentInset.bottom(bottomInset)
}
if let duration = duration {
UIView.animate(withDuration: duration) { [weak self] in self?.updateInsets(insets: insets, scrollView: scrollView) }
} else {
updateInsets(insets: insets, scrollView: scrollView)
}
}
private func updateInsets(insets: UIEdgeInsets, scrollView: UIScrollView) {
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment