Created
November 9, 2017 18:46
-
-
Save srstanic/1735295c9e9d926510e875982add17a0 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
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