Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move the whole view up when the keyboard pop up? (Swift)

Tags:

swift

enter image description here

The gray box at the bottom is a text view. When I tap the text view, the keyboard will pop up from bottom. However, the text view has been covered by the pop up keyboard.

What functions should I add in order to move up the whole view when the keyboard pops up?

like image 465
elvislkm Avatar asked Apr 26 '15 11:04

elvislkm


1 Answers

To detect when a keyboard shows up you could listen to the NSNotificationCenter

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

That will call keyboardWillShow and keyboardWillHide. Here you can do what you want with your UITextfield

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            //use keyboardSize.height to determine the height of the keyboard and set the height of your textfield accordingly
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    //pull everything down again
}
like image 80
milo526 Avatar answered Oct 23 '22 01:10

milo526