Skip to content

Instantly share code, notes, and snippets.

@nvkiet
Created August 20, 2014 14:16
Show Gist options
  • Save nvkiet/da5c73eab20829ce2a27 to your computer and use it in GitHub Desktop.
Save nvkiet/da5c73eab20829ce2a27 to your computer and use it in GitHub Desktop.
Hide/Show keyboard with Swift language
func handleKeyboardWillShowNotification(notification: NSNotification) {
if self.inputContainerViewBottomLayoutGuideConstraint.constant == 0 {
keyboardWillChangeFrameWithNotification(notification, showKeyboard: true)
scrollBubbleTableViewToBottomAnimated(true)
}
}
func handleKeyboardWillHideNotification(notification: NSNotification) {
if self.inputContainerViewBottomLayoutGuideConstraint.constant > 0 {
keyboardWillChangeFrameWithNotification(notification, showKeyboard: false)
}
}
func keyboardWillChangeFrameWithNotification(notfication: NSNotification, showKeyboard: Bool) {
let userInfo = notfication.userInfo!
let kbSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue().size
var animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue
if showKeyboard {
// Convert the keyboard frame from screen to view coordinates.
let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue()
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window)
let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)
let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y
// The input container view should be adjusted, update the constant for this constraint.
self.inputContainerViewBottomLayoutGuideConstraint.constant -= originDelta
} else {
self.inputContainerViewBottomLayoutGuideConstraint.constant = 0
}
UIView.animateWithDuration(animationDuration, animations: {
var inputContainerFrame = self.inputContainerView.frame
var tableFrame = self.tableView.frame
if showKeyboard {
inputContainerFrame.origin.y -= kbSize.height
tableFrame.size.height -= kbSize.height
} else {
inputContainerFrame.origin.y += kbSize.height
tableFrame.size.height += kbSize.height
}
self.inputContainerView.frame = inputContainerFrame
self.tableView.frame = tableFrame
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment