【问题标题】:Handle another app's obscuring keyboard on iPad split view (iOS 9 multitasking)在 iPad 拆分视图上处理另一个应用程序的模糊键盘(iOS 9 多任务处理)
【发布时间】:2016-08-07 14:54:42
【问题描述】:

以前,如果一个人在自己的应用程序上显示一个键盘,则会将所有内容嵌入UIScrollView 并调整contentInset 以防止内容被键盘遮挡。

现在在 iOS 9 上使用拆分视图多任务处理,键盘可能随时出现并保持可见,即使用户不再与其他应用交互。

问题

有没有一种简单的方法来调整所有不希望键盘可见并且不开始将所有内容嵌入到滚动视图中的视图控制器?

【问题讨论】:

  • 你能找到这个问题的答案吗?
  • 添加了我的解决方案。

标签: ios ipad keyboard multitasking splitview


【解决方案1】:

秘诀是收听UIKeyboardWillChangeFrame 通知,每当键盘在您的应用或与您的应用并行运行的其他应用中显示/隐藏时触发该通知。

我创建了这个扩展,以便于开始/停止观察这些事件(我在viewWillAppear/Disappear 中调用它们),并轻松获得通常用于调整底部的obscuredHeight contentInset你的表/集合/滚动视图。

@objc protocol KeyboardObserver
{
    func startObservingKeyboard() // Call this in your controller's viewWillAppear
    func stopObservingKeyboard() // Call this in your controller's viewWillDisappear
    func keyboardObscuredHeight() -> CGFloat
    @objc optional func adjustLayoutForKeyboardObscuredHeight(_ obscuredHeight: CGFloat, keyboardFrame: CGRect, keyboardWillAppearNotification: Notification) // Implement this in your controller and adjust your bottom inset accordingly
}

var _keyboardObscuredHeight:CGFloat = 0.0;

extension UIViewController: KeyboardObserver
{
    func startObservingKeyboard()
    {
        NotificationCenter.default.addObserver(self, selector: #selector(observeKeyboardWillChangeFrameNotification(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func stopObservingKeyboard()
    {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func observeKeyboardWillChangeFrameNotification(_ notification: Notification)
    {
        guard let window = self.view.window else {
            return
        }

        let animationID = "\(self) adjustLayoutForKeyboardObscuredHeight"
        UIView.beginAnimations(animationID, context: nil)
        UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).intValue)!)
        UIView.setAnimationDuration((notification.userInfo![UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).doubleValue)

        let keyboardFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
        _keyboardObscuredHeight = window.convert(keyboardFrame!, from: nil).intersection(window.bounds).size.height
        let observer = self as KeyboardObserver
        observer.adjustLayoutForKeyboardObscuredHeight!(_keyboardObscuredHeight, keyboardFrame: keyboardFrame!, keyboardWillAppearNotification: notification)

        UIView.commitAnimations()
    }

    func keyboardObscuredHeight() -> CGFloat
    {
        return _keyboardObscuredHeight
    }
}

【讨论】:

  • 当应用程序启动时键盘已经存在时,会发现这种情况吗?如果没有,您是如何解决的?
  • 我在viewWillAppear@PeterJohnson 上打过一次keyboardObscuredHeight()
猜你喜欢
  • 2015-09-10
  • 2016-02-13
  • 2015-12-16
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
相关资源
最近更新 更多