仅使用UIKeyboardWillChangeFrameNotification通知

Fat*_*tie 12 uikeyboard nsnotification iphone-softkeyboard ios8

考虑键盘的新QuickType部分.

为这件事千真万确可以使用只有一个通知UIKeyboardWillChangeFrameNotification,

并且只是"不打扰""旧"UIKeyboardWillShowNotification和UIKeyboardWillHideNotification?

测试似乎表明它完美运行,使用keyboardFrameDidChange - 但我们可能会遗漏一些东西?

BTW这里是一个如何使用UIKeyboardWillChangeFrameNotification的例子 /sf/answers/1835871271/

ada*_*man 35

更新于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,
    )
}
Run Code Online (Sandbox Code Playgroud)

self.formContainerBottomConstraint是一个NSLayoutConstraint将我(虚构)形式的底部绑定到我视图底部的东西.键盘出现时,此代码会向上显示动画,当键盘消失时,该代码会向下动画.

所有的通过使用的组合在IOS <8是可能的UIKeyboardWillShowNotificationUIKeyboardWillHideNotification.但!正如您所说,iOS 8引入了QuickType部分,可以由用户折叠或展开.这个解决方案非常通用,可让您的应用程序响应操作系统引发的任何键盘更改.