简体   繁体   中英

How to Preserve state of UIView Controller when it come back from Background

I have created one login Page which have two uiTextField and Login Button. When you try to login Keyboard hide textfield and button, So I have used below code to move up and down view controller from textfield delegate methods.

-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
    int movementDistance = -130; // tweak as needed
    float movementDuration = 0.3f; // tweak as needed
    int movement = (up ? movementDistance : -movementDistance);
    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);

    [UIView commitAnimations];

}

It works fine. But when i close app by home button and restart again it not preserve view controller position, Keyboard is still display but position of view controller changed to default.

Declare a NSNotification in ViewDidLoad of your View Controller class ,when the application will become active it will call your desire method.


-(void)viewDidLoad
            {

              [[NSNotificationCenter defaultCenter]addObserver:self
                                                 selector:@selector(refreshViewOnActive:)
                                                     name:UIApplicationDidBecomeActiveNotification
                                                   object:nil];


        // write rest of your code
            }

 - (void)refreshViewOnActive:(NSNotification *)notification {
       if( [textField isFirstResponder]) // check whether keyboard is open or not / or editing is enabled for your textfeild 
          {
            [self animateTextField:textField up:true]; //call your desired method
          }
    }

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