iosswiftkeyboardtextfieldkeyboard-input

Swift - Get keyboard input as the user is typing


I have an app in swift, where the texfield is located at the bottom of the screen, and when the user tries to type anything, the keyboard covers the textfield, so the user is unable to see what he/she is typing. To solve this, I would like to get the keyboard input from the user, with every stroke/"type" (everytime the user presses a key), and then display it onto a view, which is located just above the keyboard. If this is not possible, or very complex, you are more than welcome to suggest alternative solutions.


Solution

  • You need to register as observer for notifications to see when the keyboard appears and disappears. Then you would move your view up on show, or restore it to original on hide.

    My implementation moves the whole view up by keyboard height, but if you want you can just move UITextField up.

    You can take a look at this tutorial, or see my implementation in the answer:

    http://www.ioscreator.com/tutorials/move-view-behind-keyboard-ios8-swift

    Add observers in viewDidAppear

    override func viewWillAppear(animated:Bool) {
        super.viewWillAppear(animated)
    
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    

    You then need the methods to move the view in keyboardWillShow and keyboardWillHide new methods.

    @objc func keyboardWillShow(_ notification: NSNotification) {
        let info = notification.userInfo!
        let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    
        let keyboardHeight:CGFloat = keyboardSize.height
    
        //let animationDuration:CGFloat = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! CGFloat
    
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseInOut, animations: {
            self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight)
            }, completion: nil)
    
    }
    

    And to move the view to original state:

    @objc func keyboardWillHide(_ notification: NSNotification) {
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseInOut, animations: {
            self.view.transform = CGAffineTransform.identity
            }, completion: nil)
    }
    

    And at the end remove the observer in viewDidDisappear

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }