Last active
November 24, 2016 11:16
-
-
Save danielgarbien/89a8485e6ed0349328f747afe3e3ff28 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 Foundation | |
import UIKit | |
/** | |
* Coordinates contentInset on scroll view to always show full content on keyboard appearing. | |
*/ | |
class KeyboardAwareScrollViewCoordinator: NSObject { | |
let scrollView: UIScrollView | |
private let originalContentInset: UIEdgeInsets | |
init(scrollView: UIScrollView) { | |
self.scrollView = scrollView | |
originalContentInset = scrollView.contentInset | |
super.init() | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) | |
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) | |
} | |
func keyboardWillHide(notification: NSNotification) { | |
self.scrollView.contentInset = originalContentInset | |
} | |
func keyboardWillShow(notification: NSNotification) { | |
guard let keyboardFrameEnd = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect, | |
// Better solution to get a window? scrollView.window might not be in place yet | |
let scrollViewRect = UIApplication.shared.keyWindow?.convert(scrollView.bounds, from: scrollView) else { | |
return | |
} | |
let intersection = scrollViewRect.intersection(keyboardFrameEnd) | |
// increase content inset with a height covered by a keyboard | |
scrollView.contentInset = originalContentInset | |
scrollView.contentInset.bottom += intersection.height > 0 ? intersection.height : 0 | |
scrollView.scrollIndicatorInsets = scrollView.contentInset | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment