我有一个BaseViewController,其默认方法为ApplicationDidEnterForeground()。 ContactController是从BaseViewController派生的,我想在ContactController自己的ApplicationDidEnterForeground()定义中调用另一个方法。
所以现在我将:baseViewController.ApplicationDidEnterForeground()作为
public virtual void ApplicationDidEnterForeground{
//What do i put here to invoke derived class
}
ContactController.ApplicationDidEnterForeground()是重写void
在ContactController中
public override void ApplicationDidEnterForeground()
{
base.ApplicationDidEnterForeground();
ReloadTableView();
}
现在,在我的iOS设备上,我在两个方法上都设置了断点。 但是,只有BaseViewController被调用,并且当我的应用程序从后台到前台时,我不能使用ReloadTableView()。
原因:与Android不同,在iOS中,生命周期UIViewController没有像ApplicationDidEnterForeground
这样的方法。 因此,当应用程序从后台转到前台时,该方法将永远不会被调用。
解决方案:
整个应用程序的生命周期在AppDelegation
和SceneDelegation
(iOS 13.0之后)中。
您需要在相关方法中推送通知,并在您的ViewController中处理它。
[Export("applicationWillEnterForeground:")]
public void AppWillEnterForeground (UIApplication application)
{
NSNotification notification = NSNotification.FromName("WillEnterForeground", null);
NSNotificationCenter.DefaultCenter.PostNotification(notification);
}
[Export ("sceneWillEnterForeground:")]
public void WillEnterForeground (UIScene scene)
{
NSNotification notification = NSNotification.FromName("WillEnterForeground", null);
NSNotificationCenter.DefaultCenter.PostNotification(notification);
}
在ViewController中
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("WillEnterForeground"),(notify)=> {
// refresh table here
});
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
NSNotificationCenter.DefaultCenter.RemoveObserver(this, "WillEnterForeground", null);
}
您需要在每个ViewController中注册通知,以便可以处理不同的逻辑。