Here's my function that animates my view
func animateViewMoving (up:Bool, moveValue :CGFloat) {
let movementDuration:NSTimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
self.view.setNeedsLayout()
UIView.animateWithDuration(movementDuration, animations: {
self.view.layoutIfNeeded()
self.view.frame.origin.y += movement
})
}
I call this function on these two functions of UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 200)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 200)
}
The problem is this- Whenever I run my build and open the view for the first time, the view shifts up on pressing the textField and shifts down when editing the textField ends. However if I go back to a previous view and enter the view again, the view does not shift up on pressing the textField. Why is animateWithDuration
working irregularly?
Sorry I don't know swift so I'll just write my solution in objective-C.
I assume that you are using AutoLayout. If that's the case I suggest that when you animate a view, you animate it's constraints, not the frame of the view. I encountered a lot of problems before when I animate the frame of the view.
Here's a sample:
- (void)moveSubview
{
_subviewLeadingSuperLeading.constant = 20; //just a sample to move the subview horizontally.
[UIView animateWithDuration:0.5 animations:^
{
[self.view layoutIfNeeded];
}
completion:^(BOOL isFinished)
{
//Do whatever you want
}];
}
I hope this will help you. :)