Element at the bottom of view disappear after hidi

2019-06-05 04:47发布

问题:

I have 2 button at the bottom of my screen.I implement the code below in order to show and hide keyboard but do not cover my 2 button at the bottom.

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

With the code above,I successfully show and hide the keyboard without cover any element at the bottom.

But strange thing happen,when I tapped the textview 2 times,the keyboard is hide but the 2 button at bottom of screen is disappear.

So my question is,why the element will disappear when hide the keyboard? And how to solve it??

回答1:

Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey as UIKeyboardFrameBeginUserInfoKey can return different values in keyboardWillShow and keyboardWillHide

UIKeyboardFrameBeginUserInfoKey – frame of the keyboard at the beginning of the current keyboard state change. UIKeyboardFrameEndUserInfoKey – frame of the keyboard at the end of the current keyboard state change.