Last active
April 18, 2019 02:00
-
-
Save mechawrench/3b56bfb741942ea8292b8511c58f974b to your computer and use it in GitHub Desktop.
Updated for Swift 5 compatibility
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
// | |
// KeyboardBoundView.swift | |
// Mechawrench | |
// | |
// Created by Mechawrench on 4/17/19. | |
// Copyright © 2019 Mechawrench. All rights reserved. | |
// | |
import UIKit | |
extension UIView { | |
func bindToKeyboard(){ | |
NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) | |
} | |
@objc func keyboardWillChange(_ notification: NSNotification) { | |
let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double | |
let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt | |
let curFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue | |
let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue | |
let deltaY = targetFrame.origin.y - curFrame.origin.y | |
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: { | |
self.frame.origin.y += deltaY | |
},completion: {(true) in | |
self.layoutIfNeeded() | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment