如何从后台返回时保留UIView控制器的状态

时间:2015-05-16 06:09:46

标签: ios objective-c uiview uiviewcontroller uiviewanimation

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

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

}

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

1 个答案:

答案 0 :(得分:1)

在View Controller类的ViewDidLoad中声明NSNotification ,当应用程序变为活动状态时,它将调用您的欲望方法。

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