1、先添加约束,这里用图上注册按钮到view底部的约束
2、实现代码
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "keyboardWillChange:",
name: UIKeyboardWillChangeFrameNotification, object: nil)
}
/**
*键盘改变
*/
func keyboardWillChange(notification: NSNotification) {
if let userInfo = notification.userInfo,
value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
let frame = value.CGRectValue()
var intersection = CGRectIntersection(frame, self.view.frame)
//当键盘消失,让view回归原始位置
if intersection.height == 0.0 {
intersection = CGRect(x: intersection.origin.x, y: intersection.origin.y, width: intersection.width, height: 100)
}
UIView.animateWithDuration(duration, delay: 0.0,
options: UIViewAnimationOptions(rawValue: curve), animations: {
_ in
//改变下约束
self.bottomConstraint.constant = CGRectGetHeight(intersection)
self.view.layoutIfNeeded()
}, completion: nil)
}
}