Skip to content

Instantly share code, notes, and snippets.

@bleft
Created June 26, 2015 10:41
Show Gist options
  • Save bleft/967078a6543a5b01631c to your computer and use it in GitHub Desktop.
Save bleft/967078a6543a5b01631c to your computer and use it in GitHub Desktop.
move hidden text fields up if keyboard appears
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillShow:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillHide:", name: UIKeyboardDidHideNotification, object: nil)
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//MARK: handling hidden textfields
public func textFieldDidBeginEditing(textField: UITextField) {
activeTextField = textField
}
public func textFieldDidEndEditing(textField: UITextField) {
}
public func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func keyBoardWillShow(notification: NSNotification){
if let size = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
keyboardSize = size
}
moveUp()
}
func keyBoardWillHide(notification: NSNotification){
moveDown()
}
func moveUp(){
if view.frame.origin.y == 0 {
let textFeldOriginBottom = activeTextField!.frame.origin.y + addressTextField.frame.height
let position = view.frame.height - textFeldOriginBottom
let offset = position - keyboardSize!.height
if offset < 0 {
var frame = view.frame
frame.origin.y = offset - 8
UIView.animateWithDuration(0.28, animations: { () -> Void in
self.view.frame = frame
})
}
}
}
func moveDown(){
if view.frame.origin.y != 0 {
var frame = self.view.frame
frame.origin.y = 0
UIView.animateWithDuration(0.28, animations: { () -> Void in
self.view.frame = frame
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment