Swift: How to move whole screen up when keyboard shows?

I pretty sure all of you know how to do it in Objective C, but in Swift 2.x this is even simpler.

First you need to subscribe to  keyboardWillShow and keyboardWillHide events, which is achieved a bit different then in ObjC:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil);

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil);

Since we are using Swift 2.2 here, note different #selector. Where “MyViewController” is you view controller class name. Next and last step is to add functions for handling screen movement:

func keyboardWillShow(notification: NSNotification) {
        let keyboardHeight = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.height
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.window?.frame.origin.y = -1 * keyboardHeight!
            self.view.layoutIfNeeded()
        })
    }
func keyboardWillHide(notification: NSNotification) {
        UIView.animateWithDuration(0.1, animations: { () -> Void in
            self.view.window?.frame.origin.y = 0
            self.view.layoutIfNeeded()
        })
    }

This will work without adding any scroll views, just out of the box.

Leave a Reply