应用恢复时重新加载 ViewController

Re-load ViewController when app is resumed

我的应用只有一个 ViewController,因此只有一个 ViewController.swift

我希望在用户恢复应用程序(多任务处理)时重新加载 ViewControllerviewDidLoad() 函数中的初始化代码不会在应用程序恢复时触发。我希望此代码在应用程序恢复时触发,因此我想在应用程序恢复时重新加载 ViewController

在 Swift 中是否有一种优雅的方法来做到这一点?

谢谢。

您可以通过两种不同的方式执行此操作。

1.) viewController中有一个函数 viewWillAppear 尝试在这个函数中使用重新加载功能。每次出现视图时都会调用它。

2.) appDelegate 中有一个函数 applicationWillEnterForeground 尝试使用此函数中的重新加载功能。每次应用程序从后台模式变为 return 时都会调用它。

我希望这会有所帮助。谢谢

进入您的应用 delegate.m 文件

- (void)applicationWillEnterForeground:(UIApplication *)application {
// This method gets called every time your app becomes active or in foreground state.
[[NSNotificationCenter defaultCenter]postNotificationName:@"appisactive" object:nil];
}

转到您的视图 controller.m 文件,假设您希望每次用户从后台返回到前台时更改标签的文本。 默认情况下,文本的标签是这样的。

@implementation ViewController{
UIlabel *lbl;
}
-(void)viewDidLoad{
lbl = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 75, 30)];
lbl.text = @"text1";
[self.view addSubview:lbl];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textChange) name:@"appisactive" object:nil];
//this view controller is becoming a listener to the notification "appisactive" and will perform the method "textChange" whenever that notification is sent.
}

终于

-(void)textChange{
lbl.text = @"txt change";
}

实施这些 运行 项目后。 Command + H go 使应用程序进入后台而不在 Xcode 中停止。 然后按Command + H + H(连续2次)打开应用程序,你会注意到标签文字的变化。

这只是一个演示,目的是让您掌握应用程序委托通知的概念。

您可以将观察者添加到您的视图控制器,以便在您的应用进入前台时发出通知。每当您的应用程序进入前台时,此方法 reloadView 将被观察者调用。请注意,当视图第一次加载时,您必须自己调用此方法 self.reloadView()

这是 Swift 代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.reloadView()

    NSNotificationCenter.defaultCenter().addObserver(self,
     selector: "reloadView",
     name: UIApplication.willEnterForegroundNotification,
     object: nil)
}

func reloadView() {
    //do your initalisations here
}