Peter Pik
Peter Pik

Reputation: 11193

Programmatically get keyboard frame in Swift

I'm having a UITableView where I want to show the keyboard. This is hiding my last row and therefore I would like to get the keyboard frame and then calculate the size of the cell.

How can I get the frame of the keyboard programmatically in Swift?

Upvotes: 2

Views: 7225

Answers (2)

akashivskyy
akashivskyy

Reputation: 45180

You need to listen to UIResponder.keyboardWillChangeFrameNotification notifications in your view controller:

let observer = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil) { notification in
    let frame = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
    // do something with the frame
}

And don't forget to remove the observer later so that it doesn't cause any memory issues (such as strong reference cycles or even crashes):

NotificationCenter.default.removeObserver(observer)

Upvotes: 13

justColbs
justColbs

Reputation: 1872

In Swift 2.0, use the following to add an observer in viewDidLoad()

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

The second method still works in Swift 2.0

Upvotes: 8

Related Questions