Last active
May 31, 2019 10:51
-
-
Save AmirDaliri/a34a26859a008e5f38cd7eadcaa4b49c to your computer and use it in GitHub Desktop.
Keyboard Helpers
This file contains hidden or 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 ViewController: UIViewController, UITextFieldDelegate { | |
@IBOutlet weak var yourBottomConstraint: NSLayoutConstraint! | |
// MARK: - Lifecycle Methods | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// I'm Here... | |
} | |
override func viewWillAppear(_ animated: Bool) { | |
self.registerForKeyboardNotifications() | |
} | |
override func viewWillDisappear(_ animated: Bool) { | |
self.deregisterFromKeyboardNotifications() | |
} | |
override func touchesBegan(_: Set<UITouch>, with: UIEvent?) { | |
self.view.endEditing(true) | |
} | |
// MARK: - Keyboard Helpers | |
func registerForKeyboardNotifications() { | |
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) | |
} | |
func deregisterFromKeyboardNotifications() { | |
NotificationCenter.default.removeObserver(self) | |
} | |
@objc func keyboardNotification(_ notification: Foundation.Notification) { | |
if let userInfo = notification.userInfo { | |
let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue | |
let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 | |
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber | |
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions().rawValue | |
let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) | |
if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height { | |
self.scrollViewBottomConstraint?.constant = 24.0 | |
} else { | |
self.scrollViewBottomConstraint?.constant = endFrame!.size.height + 10 | |
} | |
UIView.animate(withDuration: duration, | |
delay: TimeInterval(0), | |
options: animationCurve, | |
animations: { self.view.layoutIfNeeded() }, | |
completion: nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment