简体   繁体   中英

Keyboard hiding textfield animation for another View

When I press my textfield, the keyboard hides it. So I have implemented this code to "scroll" the view up:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    const int movementDistance = 80; // tweak as needed
    const float movementDuration = 0.3f; // tweak as needed

    int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

The UIView I'm trying to do this on is in another nib. I think since I have two UIViews, the program is getting confused and doesn't know which one to set the animation to.

I don't get any errors, but the animation isn't happening.

I've declared the UIView "surveyPage" for the view I'm trying to animate. Is there somewhere in the code above where I have to specify the UIView I want to animate?

Update:

The suggestion below didn't work for me. I tried changing self.view to surveyPage.

Above the code I posted above, I have this in my program:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

The above code works without a problem, yet the animation does not.

You're specifying the UIView here:

self.view.frame = CGRectOffset(self.view.frame, 0, movement);

it's self.view .

Try:

[UIView animateWithDuration:movementDuration animations:^{
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
}];

instead of

[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM