Skip to content

Instantly share code, notes, and snippets.

@srstanic
Created November 9, 2017 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srstanic/1735295c9e9d926510e875982add17a0 to your computer and use it in GitHub Desktop.
Save srstanic/1735295c9e9d926510e875982add17a0 to your computer and use it in GitHub Desktop.
import UIKit
class KeyboardAvoider {
init(for scrollView: UIScrollView) {
self.scrollView = scrollView
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(self.onKeyboardShow(notification:)),
name: .UIKeyboardWillShow,
object: nil
)
notificationCenter.addObserver(
self,
selector: #selector(self.onKeyboardHide(notification:)),
name: .UIKeyboardWillHide,
object: nil
)
}
@objc private func onKeyboardShow(notification: Notification) {
guard !keyboardShown else {
return
}
keyboardShown = true
if let keyboardRect = notification.keyboardEndFrame {
let keyboardRectInScrollView = scrollView.convert(keyboardRect, from: nil)
let scrollViewBottom = scrollView.bounds.maxY
let keyboardTop = keyboardRectInScrollView.minY
if scrollViewBottom > keyboardTop {
let heightCoveredWithKeyboard = scrollViewBottom - keyboardTop
scrollViewContentInset = scrollView.contentInset.bottom
scrollView.contentInset.bottom = heightCoveredWithKeyboard
scrollViewIndicatorInset = scrollView.scrollIndicatorInsets.bottom
scrollView.scrollIndicatorInsets.bottom = heightCoveredWithKeyboard
}
}
}
@objc private func onKeyboardHide(notification: Notification) {
keyboardShown = false
scrollView.contentInset.bottom = scrollViewContentInset
scrollView.scrollIndicatorInsets.bottom = scrollViewIndicatorInset
}
private var keyboardShown = false
private var scrollViewContentInset: CGFloat = 0
private var scrollViewIndicatorInset: CGFloat = 0
private var scrollView: UIScrollView
}
private extension Notification {
var keyboardEndFrame: CGRect? {
let userInfo = self.userInfo
return userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment