【问题标题】:Element at the bottom of view disappear after hiding the keyboard Swift 4隐藏键盘Swift 4后视图底部的元素消失
【发布时间】:2018-01-20 16:55:32
【问题描述】:

我的屏幕底部有 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。
  • @ArunGJ 是有效的..谢谢..你可以回答一下,所以我可以接受吗??

标签: ios keyboard swift4


【解决方案1】:

使用UIKeyboardFrameEndUserInfoKey 代替UIKeyboardFrameBeginUserInfoKey 因为UIKeyboardFrameBeginUserInfoKey 可以在keyboardWillShowkeyboardWillHide 中返回不同的值

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多