Last active
January 25, 2021 16:44
-
-
Save drewster99/007ce364a5851fe2e1f0639a266383bf to your computer and use it in GitHub Desktop.
Move views out of the way when keyboard appears, Swift 4.1, using Auto-Layout / Interface Builder / Storyboard
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
{ | |
// Move views when keyboard appears/disappears | |
// Snipped from ViewController.swift | |
// This constraint should be tied to the top superview or safe area in Storybaord | |
@IBOutlet weak var closeButtonTopConstraint: NSLayoutConstraint! | |
private var topConstraintOriginalConstant: CGFloat? | |
private var topConstraintScrolledConstant: CGFloat = 0 | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) | |
} | |
@objc func keyboardWillShow(_ sender: NSNotification) { | |
if topConstraintOriginalConstant == nil { | |
topConstraintOriginalConstant = closeButtonTopConstraint.constant | |
topConstraintScrolledConstant = topConstraintOriginalConstant! - 200 | |
} | |
closeButtonTopConstraint.constant = topConstraintScrolledConstant | |
UIViewPropertyAnimator(duration: 0.25, curve: .easeOut) { | |
self.view.layoutIfNeeded() | |
}.startAnimation() | |
} | |
@objc func keyboardWillHide(_ sender: NSNotification) { | |
closeButtonTopConstraint.constant = topConstraintOriginalConstant ?? closeButtonTopConstraint.constant | |
UIViewPropertyAnimator(duration: 0.25, curve: .easeOut) { | |
self.view.layoutIfNeeded() | |
}.startAnimation() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment