Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Move views out of the way when keyboard appears, Swift 4.1, using Auto-Layout / Interface Builder / Storyboard
{
// 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
You can’t perform that action at this time.