I am trying to raise the View when a Keypad comes up, but it just bounces back. If I give CGRectOffset
a positive value for Y (moving the View down), then it stays.
@IBOutlet weak var PPI: MainTextFields!
var KbHeight: CGFloat!
//----------------------------------------------
func animateTextField(up: Bool) {
let TFMovement = (up ? -KbHeight : KbHeight)
UIView.animateWithDuration(0.7, animations: {
self.view.frame = CGRectOffset(self.view.frame, 0, TFMovement)
})
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
KbHeight = keyboardSize.height
self.animateTextField(true)
}
}
}
func keyboardWillHide(notification: NSNotification) {
self.animateTextField(false)
}
//----------------------------------------------
// Touch Outside Keypad to leave it
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
// For TextField Movement
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// For TextField Movement
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
PPI.delegate = self
}
Am I doing something wrong with the CGRectOffset
in the keyboardWillShow
function? I am relatively new to Swift and got this from a tutorial, but just doesn't seem to work properly.
It turned out to be because of the Auto-Layout Constraint I had to the Top Margin, so the Constant of that Constraint needed to be changed and the line:
self.view.frame = CGRectOffset(self.view.frame, 0, TFMovement)
was not needed at all.