My view keeps moving up when tapping my textField or using the keyboard using NS notification

127 Views Asked by At

I have a stack view with some texField's and a button inside, this is used for a login page

I also have a button at the bottom of the view this is used to present another view controller, this button works fine

I've set up a tapGesture recogniser that if you tap anywhere on the view the keyboard should dismiss and the view go back to its original constraints this also works fine

I've set up NS notification and in my function keyboardWillShow, when I tap in a textField the view moves up as I want it to

My problem is the moment i tap another textField or i start typing the view moves up again I'm not sure why this is

It looks like for some reason the function gets called every time I tap on a different text field or I use the keyboard I can't see why this is happening Any help would be appreciated because I'm new to switch

    view.addSubview(alreadyHaveAccountButton)
    alreadyHaveAccountButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 5, paddingRight: 0, width: 0, height: 60)



    let stack = UIStackView(arrangedSubviews: [emailTextfield,passwordTextfield,fullNameTextfield,signUpButton])
    stack.axis = .vertical
    stack.spacing = 20
    stack.distribution = .fillEqually

    view.addSubview(stack)
    stack.anchor(top: nil, left: view.leftAnchor, bottom: alreadyHaveAccountButton.topAnchor, right:
        view.rightAnchor, paddingTop: 0, paddingLeft: 20, paddingBottom: 50, paddingRight: 20, width: 0, height: 0)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIWindow.keyboardWillShowNotification, object: nil)

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


@objc func keyboardWillShow(notification: NSNotification) {

    let notification = notification.userInfo
    let keyboardFrame = notification?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
    let keyboardFrameSize = keyboardFrame.cgRectValue

    view.frame.origin.y -= keyboardFrameSize.height
}


@objc func keyboardWillHide(notification: NSNotification) {
    let notification = notification.userInfo
    let keyboardFrame = notification?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue
    let keyboardFrameSize = keyboardFrame.cgRectValue

    view.frame.origin.y += keyboardFrameSize.height

}
0

There are 0 best solutions below