Search code examples
iosswiftuikit

How to make it appear in its original position when view appears?


I created a textfield and wrote the code below to make the textfield appear right above the keyboard when the keyboard appears. But the textfield appears from top to bottom I hope it shows up right away What should I do?

inputTextField = UITextField(frame: CGRect(x:0, y: 0, width: UIScreen.main.bounds.width, height: 50))
inputTextField.font = UIFont.systemFont(ofSize: 15)
inputTextField.backgroundColor = .white
inputTextField.borderStyle = UITextField.BorderStyle.bezel
inputTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center

view.addSubview(inputTextField)

registerKeyboardNotifications()
func registerKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
    
@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let textFieldOrigin = CGPoint(x: 0, y: keyboardSize.origin.y - inputTextField.frame.height)
        
        inputTextField.frame.origin = textFieldOrigin
    }
}

@objc func keyboardWillHide(_ notification: Notification) {
    inputTextField.frame.origin = CGPoint(x: 0, y: 5000)
    inputTextField.resignFirstResponder()
}

Solution

  • UI changes are automatically animated when the keyboard is being shown.

    Add an observer for keyboardDidShowNotification -- set the hidden textfield's origin in willShow and then set .isHidden = false in didShow.

    Here's an example:

    class ViewController: UIViewController {
        
        var inputTextField: UITextField!
        var showBtn: UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            inputTextField = UITextField(frame: CGRect(x:0, y: 0, width: UIScreen.main.bounds.width, height: 50))
            inputTextField.font = UIFont.systemFont(ofSize: 15)
            inputTextField.backgroundColor = .white
            inputTextField.borderStyle = UITextField.BorderStyle.bezel
            inputTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
    
            // start with text field hidden
            inputTextField.isHidden = true
            
            view.addSubview(inputTextField)
            
            var cfg = UIButton.Configuration.filled()
            cfg.title = "Show"
            showBtn = UIButton(configuration: cfg, primaryAction: UIAction() { _ in
                if self.inputTextField.isFirstResponder {
                    self.inputTextField.resignFirstResponder()
                } else {
                    self.inputTextField.becomeFirstResponder()
                }
            })
            showBtn.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(showBtn)
            showBtn.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0).isActive = true
            showBtn.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0).isActive = true
    
            registerKeyboardNotifications()
            
        }
        
        func registerKeyboardNotifications() {
            // Register for keyboard notifications
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    
            // also add a keyboardDidShowNotification observer
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
        }
        
        @objc func keyboardWillShow(_ notification: Notification) {
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
                let textFieldOrigin = CGPoint(x: 0, y: keyboardSize.origin.y - inputTextField.frame.height)
    
                // set the hidden textfield's origin
                self.inputTextField.frame.origin = textFieldOrigin
            }
        }
        @objc func keyboardDidShow(_ notification: Notification) {
            // show the textfield
            self.inputTextField.isHidden = false
            // update the button title
            self.showBtn.configuration?.title = "Hide"
        }
        @objc func keyboardWillHide(_ notification: Notification) {
            // hide the textfield
            inputTextField.isHidden = true
            // update the button title
            self.showBtn.configuration?.title = "Show"
        }
    }