当应用恢复时重新加载ViewController

问题描述 投票:2回答:3

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

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

在Swift中,有没有一种优雅的方法?

谢谢。

ios iphone swift view uiviewcontroller
3个回答
3
投票

您可以在视图控制器中添加和观察者,以通知您的应用何时进入前台。每当您的应用进入前台时,观察者就会调用此方法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
}

0
投票

进入您的应用程序委托.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];
}

转到您的view 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可使应用程序进入后台,而无需在Xcode中停止它。然后按Command + H + H(连续2次)并打开应用程序,您会注意到标签文本的更改。

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


-1
投票

您可以用两种不同的方式来做。

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

2。)appDelegate applicationWillEnterForeground中有一个功能,请尝试在此功能中使用重载功能。每当应用程序从后台模式返回时都会调用它。

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

© www.soinside.com 2019 - 2024. All rights reserved.