Surafel Taddesse
Surafel Taddesse

Reputation: 13

Textfields escape out of view when keyboard is displayed

I have a view controller with custom cell counting textfields. I am using the code below for keyboard management but for the textfields in the upper half of the view escape up and out of view. The keyboard shifts the view upwards, pushing those textfields beyond the top margins of the view.

I am using the following code for keyboard management:

override func viewDidLoad() {
    super.viewDidLoad()
    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 the following functions:

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

@objc func keyboardWillHide(notification: NSNotification) {
    if self.view.frame.origin.y != 0 {
        self.view.frame.origin.y = 0
    }
}

Any help will be appreciated!

Upvotes: 1

Views: 29

Answers (1)

Jins George
Jins George

Reputation: 121

plz use pod 'IQKeyboardManagerSwift' and just paste the code in appdelegate

import IQKeyboardManagerSwift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        IQKeyboardManager.shared.enable = true
return true
}

Upvotes: 1

Related Questions