Skip to content

Instantly share code, notes, and snippets.

@mechawrench
Last active April 18, 2019 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mechawrench/3b56bfb741942ea8292b8511c58f974b to your computer and use it in GitHub Desktop.
Save mechawrench/3b56bfb741942ea8292b8511c58f974b to your computer and use it in GitHub Desktop.
Updated for Swift 5 compatibility
//
// 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