Skip to content

Instantly share code, notes, and snippets.

@bocato
Last active June 28, 2020 06:09
Show Gist options
  • Save bocato/4ed7ca9b9494674a6925b807986ca3fc to your computer and use it in GitHub Desktop.
Save bocato/4ed7ca9b9494674a6925b807986ca3fc to your computer and use it in GitHub Desktop.
protocol ScrollableContentKeyboardObserving {
func observeKeyboardWillShowNotification(_ scrollView: UIScrollView, onShowHandler onShow: ((CGSize?) -> Void)?)
func observeKeyboardWillHideNotification(_ scrollView: UIScrollView, onHideHandler onHide: ((CGSize?) -> Void)?)
}
extension ScrollableContentKeyboardObserving {
func observeKeyboardWillShowNotification(_ scrollView: UIScrollView, onShowHandler onShow: ((CGSize?) -> Void)? = nil) {
let block: (Notification) -> Void = { notification -> Void in
guard let keyboardFrameEndUserInfoKey = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] else { return }
let keyboardSize = (keyboardFrameEndUserInfoKey as AnyObject).cgRectValue.size
let contentInsets = UIEdgeInsets(
top: scrollView.contentInset.top,
left: scrollView.contentInset.left,
bottom: keyboardSize.height,
right: scrollView.contentInset.right
)
scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
onShow?(keyboardSize)
}
_ = NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillShowNotification,
object: nil,
queue: nil,
using: block
)
}
func observeKeyboardWillHideNotification(_ scrollView: UIScrollView, onHideHandler onHide: ((CGSize?) -> Void)? = nil) {
let block: (Notification) -> Void = { notification in
guard let keyboardFrameEndUserInfoKey = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] else { return }
let keyboardSize = (keyboardFrameEndUserInfoKey as AnyObject).cgRectValue.size
let contentInsets = UIEdgeInsets(
top: scrollView.contentInset.top,
left: scrollView.contentInset.left,
bottom: .zero,
right: scrollView.contentInset.right
)
scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
onHide?(keyboardSize)
}
_ = NotificationCenter.default.addObserver(
forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: nil,
using: block
)
}
}
extension UIScrollView {
func setContentInsetAndScrollIndicatorInsets(_ edgeInsets: UIEdgeInsets) {
contentInset = edgeInsets
scrollIndicatorInsets = edgeInsets
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment