Last active
June 28, 2020 06:09
-
-
Save bocato/4ed7ca9b9494674a6925b807986ca3fc to your computer and use it in GitHub Desktop.
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
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