0
votes

I am trying to build an input screen for the iPhone in swift. The screen has a number of input fields. Most of them on the top of the screen, but three fields are at the bottom. When the user tries to edit the text on the bottom of the screen, the keyboard will pop up and it will cover the screen. I found a simple solution to move the screen up when this happens, but the result is that the screen always moves up and the fields on top of the screen move out of reach when the user tries to edit those. for example : I want form txt1 to txt4 the view does not go up.

Is there a way to have the screen only move when the bottom fields are edited?

I have used this code I found here:

override func viewDidLoad() {

    txt1.delegate = self
    txt2.delegate = self
    txt3.delegate = self
    txt4.delegate = self
    txt5.delegate = self
    txt6.delegate = self
    txt7.delegate = self
    txt8.delegate = self
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)

}

func keyboardWillShow(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardSize.height
        }
        }

}

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

**

1
you don't need to add each textfield delegate, you only need add in the viewdidload the Notification Center for keyboard, please read this pod keyboardManagerAndres Gomez
Does this answer your question? Move view with keyboard using SwiftNoodleOfDeath

1 Answers

0
votes

I did this function to start show keyboard while I start editing on textfields:

   public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)

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

}

but here it's going for all the textfield that I have and its the same problem. how can I make it for specific textfield?