skip to Main Content

I want to move textfield up when keyword covers the textfield. Now I am facing a problem with the moving textfield up: it moves up but every time when I click one of the textfields.

How to move the textfield up only when it is covered by keyword?
Also, I have scrolling when the textfield tapped, but it does not work correctly

Here is my code:

    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)
    
    
    self.hideKeyboardWhenTappedAround()
}



@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            if view.frame.origin.y == 0 {
                self.view.frame.origin.y -= keyboardSize.height
            }
        }
    guard let userInfo = notification.userInfo else { return }
    var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    keyboardFrame = self.view.convert(keyboardFrame, from: nil)

    var contentInset:UIEdgeInsets = self.scrollView.contentInset
    contentInset.bottom = keyboardFrame.size.height + 20
    scrollView.contentInset = contentInset
}

@objc func keyboardWillHide(notification: NSNotification) {

    let contentInset:UIEdgeInsets = UIEdgeInsets.zero
    scrollView.contentInset = contentInset
    
    if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y = 0
        }
}

enter image description here

enter image description here

2

Answers


  1. Simply use this cocoapods to manage all text fields

    pod ‘IQKeyboardManagerSwift’

    1. Install pods in your project
    2. Add the below line in your AppDelegate file under the didFinishLaunchingWithOptions method

    IQKeyboardManager.shared.enable = true

    Here is a reference link — IQKeyboardManagerSwift

    Login or Signup to reply.
  2. Solutions.

    First way you can listen keyboardWillChangeFrameNotification

    Second way you can hide keywords textField.autocorrectionType = .no

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