在 Swift 4 中</p>
为键盘通知添加观察者:
- UIKeyboardDidShowNotification
- UIKeyboardDidHideNotification
通过
NSNotificationCenter.defaultCenter().addObserver(_ observer: Any,
selector aSelector: Selector,
name aName: NSNotification.Name?,
object anObject: Any?)
并实现选择器以使用键盘动画为 UI 设置动画。为了创建一个有效的曲线值,我们需要将 UIResponder.keyboardAnimationCurveUserInfoKey 移动 << 16 </p>
func keyboardWillShow(_ notification: Notification!) {
if let info = notification.userInfo {
let keyboardSize = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
let duration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
let curveVal = (info[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.intValue ?? 7 // default value for keyboard animation
let options = UIView.AnimationOptions(rawValue: UInt(curveVal << 16))
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
// any operation to be performed
}, completion: nil)
}
}