从后台返回时如何保留 UIView Controller 的状态

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

我创建了一个登录页面,其中有两个 uiTextField 和登录按钮。当您尝试登录键盘时隐藏文本字段和按钮,所以我使用下面的代码从文本字段委托方法上下移动视图控制器。

-(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];

}

它工作正常。但是当我通过主页按钮关闭应用程序并再次重新启动时,它不会保留视图控制器的位置,键盘仍然显示但视图控制器的位置更改为默认值。

在视图控制器的 ViewDidLoad 中声明一个 NSNotification class,当应用程序激活时,它将调用您想要的方法。


-(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
          }
    }