Search code examples
iosswiftuistoryboardnslayoutconstraintuikeyboard

when a keyboard shows up in my app, the button partially moves up (only the text of the button moves)


I have a button in my swift app which is in the bottom of the screen. Constraints for it are:

enter image description here

I also attached outlet for a constraint that separates my button from the bottom of the screen:

enter image description here

When I run the app, I see my button (I added some backgroun color so that my example is clearly visible):

enter image description here

now, the weird thing happens - when the keyboard reveals, the text on the button moves up, the blue background stays where it was:

enter image description here

And also the visible part of button is not clickable at all.

Is it some kind of bug or the problem in my implementation?

My code is fairly simple for that:

@IBOutlet weak var continueUsernameBottomConstraint: NSLayoutConstraint!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


    NotificationCenter.default.addObserver(self, selector: #selector(tutorialKeyboardWillAppear), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(tutorialKeyboardWillDisappear), name: .UIKeyboardWillHide, object: nil)

}


func tutorialKeyboardWillAppear(notification: NSNotification){
    print("KEYBOARD APPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    continueUsernameBottomConstraint.constant = view.bounds.height - endFrame.origin.y

    self.view.layoutIfNeeded()
}

func tutorialKeyboardWillDisappear(notification: NSNotification){

    print("KEYBOARD DISAPPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    continueUsernameBottomConstraint.constant = view.bounds.height - endFrame.origin.y

    self.view.layoutIfNeeded()

}

Solution

  • Use this

    func tutorialKeyboardWillAppear(notification: NSNotification){
        print("KEYBOARD APPEARS")
        let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant + CGFloat(endFrame.height)
        self.view.layoutIfNeeded()
    }
    
    func tutorialKeyboardWillDisappear(notification: NSNotification){
    
        print("KEYBOARD DISAPPEARS")
        let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant -  CGFloat(endFrame.height)
        self.view.layoutIfNeeded()
    
    }