考虑键盘的新QuickType部分。
是否只能使用UIKeyboardWillChangeFrameNotification的通知,
并且只是“不打扰”“旧”UIKeyboardWillShowNotification和UIKeyboardWillHideNotification?
测试似乎表明它完美运行,仅使用keyboardFrameDidChange - 但我们可能会遗漏一些东西?
BTW这里是一个如何使用UIKeyboardWillChangeFrameNotification https://stackoverflow.com/a/26226732/294884的例子
更新于2018-05-25的Swift 4
这绝对是可能的,可以将你的代码减少一半。以下示例使用自动布局进行大量繁重工作。
NotificationCenter.default.addObserverForName(
NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil,
queue: nil
) { (notification) in
guard let userInfo = notification.userInfo,
let frameEnd = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect,
let animationCurveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int,
let animationCurve = UIViewAnimationCurve(rawValue: animationCurveValue),
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval
else { return }
// Convert the frame rects you're interested in to a common coordinate space
let keyboardRect = self.view.convert(frameEnd, from: nil)
let formContainerRect = self.view.convert(self.formContainerView.frame, from: nil)
// Calculate their intersection and adjust your constraints accordingly
let intersection = keyboardRect.intersection(formContainerRect)
if !intersection.isNull {
// Some overlap
// Just an example; what exactly you do here will vary
self.formContainerBottomConstraint.constant = intersection.size.height
} else {
// No overlap
// Reset your views to their default positions
self.formContainerBottomConstraint.constant = 0
}
var options: UIViewAnimationOptions = []
switch animationCurve {
case .easeInOut:
options.insert(.curveEaseInOut)
case .easeIn:
options.insert(.curveEaseIn)
case .easeOut:
options.insert(.curveEaseOut)
case .linear:
options.insert(.curveLinear)
}
// You may also want to add additional animation options; do that here
options.insert(.preferredFramesPerSecond60)
UIView.animateWithDuration(
animationDuration,
delay: 0,
options: options,
animations: {
self.view.layoutIfNeeded()
},
completion: nil,
)
}
self.formContainerBottomConstraint
是一个NSLayoutConstraint
,它将我(想象)形式的底部绑定到我的视图的底部。键盘出现时,此代码会向上显示动画,当键盘消失时,该代码会向下动画。
所有这些都可以通过使用UIKeyboardWillShowNotification
和UIKeyboardWillHideNotification
的组合在iOS <8中实现。但!正如您所说,iOS 8引入了QuickType部分,可以由用户折叠或展开。这个解决方案非常通用,可让您的应用程序响应操作系统引发的任何键盘更改。