![](/img/trans.png)
[英]iOS - How to re-load a different ViewController within a UITabBar
[英]Re-load ViewController when app is resumed
我的应用程序只有一个ViewController
,因此只有一个ViewController.swift
我希望在用户恢复应用程序(多任务处理)时重新加载该ViewController
。 viewDidLoad()
函数中的初始化代码在应用程序恢复时不会触发。 我希望在应用程序恢复时触发此代码,因此我想在应用程序恢复时重新加载ViewController
。
在 Swift 中有一种优雅的方法可以做到这一点吗?
谢谢你。
您可以在视图控制器中添加和观察者以通知您的应用程序何时进入前台。 每当您的应用程序进入前台时,此方法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
}
进入你的应用程序 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 使应用程序进入后台而不在 Xcode 中停止它。 然后按Command + H + H(连续2次)并打开应用程序,您会注意到标签文本的变化。
这只是一个演示,让您了解来自应用程序委托的通知的想法。
你可以用两种不同的方式来做到这一点。
1.) viewController viewWillAppear
有一个函数尝试使用该函数中的重新加载功能。 每次出现视图时都会调用它。
2.) appDelegate 中有一个函数applicationWillEnterForeground
尝试使用该函数中的重载功能。 每次应用程序从后台模式返回时都会调用它。
我希望这会有所帮助。谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.