0

I need to move up the layout when the keyboard appears and the textfield won't be shown because of the size of the keyboard. Therefore I created this:

    var activeField: UITextField!

in my ViewDidLoad:

 let center: NotificationCenter = NotificationCenter.default;
    center.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)

and here are the methods:

 func textFieldDidBeginEditing(_ textField: UITextField) {
    activeField = textField
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true

}


@objc func keyboardWillShow(notification: Notification) {
    let info: NSDictionary = notification.userInfo as! NSDictionary
    let keyboardSize =  (info[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue

    let keyboardY = self.view.frame.size.height - keyboardSize.height

    let editingTextFieldY: CGFloat = self.activeField.frame.origin.y
    if editingTextFieldY > keyboardY - 60 {

        UIView.animate(withDuration: 0.25) {
            self.view.frame = CGRect(x: 0, y: self.view.frame.origin.y - (editingTextFieldY - (keyboardY-60)), width: self.view.bounds.width, height: self.view.bounds.height)
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    UIView.animate(withDuration: 0.25, animations: {
        self.view.frame = CGRect(x:0, y:0, width: self.view.bounds.width, height: self.view.bounds.height)
    }, completion: nil)
}

the error appears at this line:

        let editingTextFieldY: CGFloat = self.activeField.frame.origin.y
Mahgolsadat Fathi
  • 3,107
  • 4
  • 16
  • 34
Dominik Hartl
  • 101
  • 11
  • In the modern era, the only way to do this is the technique of: **use autolayout perfectly for your screen. have one constraint which shapes the overall screen from the bottom. very simply just animate that ONE CONSTRAINT. and you're done - it's that easy. autolayout does everything."** Full tutorial: https://stackoverflow.com/a/41808338/294884 – Fattie Dec 16 '18 at 14:23
  • Why are you still manually showing and hiding the keyboard? If you're in a navigation view hierarchy, just set the `navigationItem.searchController` to an instance of `UISearchController` and let iOS do all the heavy lifting for you. – NRitH Dec 16 '18 at 14:43

1 Answers1

1

This textFieldDidBeginEditing isn't being called.

You need to set the delegate of the origin textfield in viewDidLoad

self.mainTexF.delegate = self
Mahgolsadat Fathi
  • 3,107
  • 4
  • 16
  • 34
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87