2

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

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

问题

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

4

1 回答 1

0

秘诀是收听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
    }
}
于 2017-04-13T14:17:42.683 回答