Tom el Safadi
Tom el Safadi

Reputation: 6776

swift keyboard moves up twice

I use the following code to move up the view when the keyboard appears. This works fine but I have the problem that if I tapp on a textfield and directly tap on the next textfield it moves my view up twice.
How can I make it moving the view up only one time?

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

func keyboardWillShow(notification: NSNotification) {
     print(self.view.frame.origin.y)


    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {

        self.view.frame.origin.y -= keyboardSize.height

    }

    print(self.view.frame.origin.y)
}

func keyboardWillHide(notification: NSNotification) {
    print("is dissapaering now")
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {

        self.view.frame.origin.y += keyboardSize.height
    }
}

Upvotes: 0

Views: 485

Answers (1)

Serneum
Serneum

Reputation: 577

It sounds like you should be checking if the keyboard is already showing before showing it again. Create a new Bool variable that tracks the state and only move the view if the Bool value is false.

Upvotes: 1

Related Questions