-1

There are several TextFields in a UIView.I want move view up when user edit TextField.And then i try it reference Move view with keyboard using Swift

My core code is below:

//MARK: Properties
@IBOutlet weak var userAccountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!

//MARK: Callback
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}

func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
            if self.view.frame.origin.y == 0{
                //self.view.frame.origin.y -= keyboardSize.height
                self.view.frame.origin.y -= 150
            }
        }
    }

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        if self.view.frame.origin.y != 0{
            //self.view.frame.origin.y += keyboardSize.height
            self.view.frame.origin.y += 150
        }
    }

}

There are two issues:

1.The keyboardSize.height with hide the keyboard is bigger than keyboardSize.height with show the keyboard.Then there will be a black field top after the keyboard hide. So now i must use a constant number.

2.The view move up after the keyboard show, it's good.But the view move down again when i type some chars or i click other TextFiled.It's good If i put these TextFields into a ScrollView.But i don't it's why.Like below picture: enter image description here

Any help would be greatly appreciated.

WangYang
  • 1
  • 2

1 Answers1

0

Your “viewDidLoad” method contains an error, you have to add and not to remove the observer, you have to remove it in “viewWillDisappear”

override func viewDidLoad() {
    super.viewDidLoad()            
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24