ios - 隐藏键盘 Swift 4 后 View 底部的元素消失

标签 ios keyboard swift4

我的屏幕底部有 2 个按钮。我实现了下面的代码以显示和隐藏键盘,但不覆盖底部的 2 个按钮。

override func viewDidLoad() {
        super.viewDidLoad()

    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)

    //here will hide the keyboard when tap the text view 2 times
    let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyBoard))
    self.statusTextView.addGestureRecognizer(tap)
}

@objc func hideKeyBoard(sender: UITapGestureRecognizer? = nil){
        statusTextView.endEditing(true)
 }

@objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

            if 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)
            }

        }
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] 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)
        }
    }

通过上面的代码,我成功地显示和隐藏了键盘,没有覆盖底部的任何元素。

但是奇怪的事情发生了,当我点击 textview 2 次时,键盘隐藏了但是屏幕底部的 2 按钮消失了。

所以我的问题是,为什么隐藏键盘时元素会消失?以及如何解决??

最佳答案

使用 UIKeyboardFrameEndUserInfoKey 而不是 UIKeyboardFrameBeginUserInfoKey 因为 UIKeyboardFrameBeginUserInfoKey 可以在 keyboardWillShowkeyboardWillHide< 中返回不同的值

UIKeyboardFrameBeginUserInfoKey – 当前键盘状态改变开始时的键盘框架。 UIKeyboardFrameEndUserInfoKey – 当前键盘状态更改结束时的键盘框架。

关于ios - 隐藏键盘 Swift 4 后 View 底部的元素消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353774/

相关文章:

iphone - 在没有 KeyboardWillShowNotification 的情况下获取键盘大小

ios - API 响应访问“发件人”和“收件人”邮件的名称

ios - 调整 super View 大小和重新布局 subview 的正确方法(在自动布局中)?

ios - UIScrollView中UITableView内容问题

ios - 进入后台时保护显示数据 : applicationDidEnterBackground

ios - iOS 应用程序中 WebView 内的电话链接

ios - 无法将数据保存到 MVC (Swift)

python - 键盘包不适用于 sudo 命令启动

ios - 将语言词典添加到 iOS 自定义键盘以用于预测(暗示)文本