skip to Main Content

I know that there are several questions on this topic, but i have not been able to find any on [SWIFT 5.0] or more, and would really appreciate your help.

I have a UITextFeild at the bottom of the screen which gets hidden every time the user clicks on it. Is there a recent method on which i can solve this hiding issue, by either the textFeild following the keyboard to the top or a sample field appearing on top of the keyboard. Any help would be greatly appreciated, thank you!

2

Answers


  1. You can use the following code:

    First, add these two lines of code in your controller viewDidLoad() method:

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    

    Second, add these two methods inside your controller:

    @objc func keyboardWillShow(notification: NSNotification) {
      
        if yourTextfield.isEditing == true
        {
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y = 64
        }
    }
    

    Enjoy :).

    Login or Signup to reply.
  2. If you use AutoLayout you may try Keyboard and KeyboardLayoutGuide from my collection of handy Swift extensions and classes called SwiftToolkit

    Add this code to your controller viewDidLoad() method:

    let keyboardGuide = KeyboardLayoutGuide()
    view.addLayoutGuide(keyboardGuide)
    
    /** 
        Your textField vertical position constraint 
        must have lower priority than this constraint
    */
    keyboardGuide.topAnchor.constraint(greaterThanOrEqualTo: textField.bottomAnchor, constant: 8).isActive = true
    

    When the keyboard appears it will push your UITextField up like this:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search