如何使键盘显示但不覆盖屏幕底部的元素Swift 4?

时间:2018-01-20 06:16:26

标签: ios keyboard swift4

我的屏幕有如下布局,顶部是TextView,底部是2个按钮:

enter image description here

我想要的是键盘出现在2按钮的底部。只要出现键盘,所需的输出就像这样:

enter image description here

因此,我在ViewController

中实施此代码
override func viewDidLoad() {
    super.viewDidLoad()

    self.statusTextView.perform(
        #selector(becomeFirstResponder),
        with: nil,
        afterDelay: 0.1)

    NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

 }

@objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }

@objc func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

通过上面的代码键盘显示在底部的2按钮下,textView也向上移动。这是输出:

enter image description here

正如您所看到的,textView也会向上移动。因此它不会出现在屏幕上。 所以我的问题是,如何使键盘显示没有覆盖底部的任何元素,也不影响元素?

从@ D.Desai实施解决方案后,我在Xcode中收到此错误

enter image description here

1 个答案:

答案 0 :(得分:2)

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
        let window = self.view.window?.frame 
        // We're not just minusing the kb height from the view height because
        // the view could already have been resized for the keyboard before
        self.view.frame = CGRect(x: self.view.frame.origin.x,
                                 y: self.view.frame.origin.y,
                                 width: self.view.frame.width,
                                 height: window.origin.y + window.height - keyboardSize.height)
    } else {
        debugPrint("We're showing the keyboard and either the keyboard size or window is nil: panic widely.")
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let viewHeight = self.view.frame.height
        self.view.frame = CGRect(x: self.view.frame.origin.x,
                                 y: self.view.frame.origin.y,
                                 width: self.view.frame.width,
                                 height: viewHeight + keyboardSize.height)
    } else {
        debugPrint("We're about to hide the keyboard and the keyboard size is nil. Now is the rapture.")
    }
}