How to solve keyboard problems in Swift 3?

前端 未结 3 1662
有刺的猬
有刺的猬 2021-01-26 08:34

The problem is that when I try to write in the text fields the keyboard cover them up. How can I scroll the text field up to see what am I writing. I have below lines of code to

3条回答
  •  时光说笑
    2021-01-26 09:22

    The easiest solution to this problem is to put all the elements into one scrollview and then add the keyboard height to the constant of the bottom of the view to superview.

    When the keyboard is shown or hidden, iOS sends out the following notifications to any registered observers:

    UIKeyboardWillShowNotification UIKeyboardDidShowNotification UIKeyboardWillHideNotification UIKeyboardDidHideNotification

    So here is what you can do:

    1. Get the size of the keyboard.
    2. Adjust the bottom content inset of your scroll view by the keyboard height.
    3. Scroll the target text field into view.

    Something like this:

     func keyboardWillShow(notification: NSNotification) {
            print("KEYBOARD WILL SHOW")
            let userInfo:NSDictionary = notification.userInfo! as NSDictionary
            let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
            let keyboardRectangle = keyboardFrame.cgRectValue
            let keyboardHeight = keyboardRectangle.height
            bottomConstraint.constant = keyboardHeight + 8
            UIView.animate(withDuration: 0.5, animations: { [weak self] in
                self?.view.layoutIfNeeded() ?? ()
            })
    
            UIView.animate(withDuration: 0.3) {
                self.view.layoutIfNeeded()
            }
        }
        func dismissKeyboard() {
            //Causes the view (or one of its embedded text fields) to resign the first responder status.
            view.endEditing(true)
            bottomConstraint.constant = 8
            UIView.animate(withDuration: 0.5, animations: { [weak self] in
                self?.view.layoutIfNeeded() ?? ()
            })
        }
    

提交回复
热议问题