【问题标题】:Re-load ViewController when app is resumed应用程序恢复时重新加载 ViewController
【发布时间】:2015-09-14 12:38:56
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: ios iphone swift view uiviewcontroller


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      进入你的应用 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];
      }
      

      转到您的视图控制器.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次)打开应用程序,你会注意到标签文本的变化。

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

      【讨论】:

      • 感谢您提供此信息。有没有办法将此代码集成到 swift 项目中?再次感谢。
      【解决方案3】:

      您可以通过两种不同的方式做到这一点。

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

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

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

      【讨论】:

      • viewWillAppear 应用程序进入前台时不会被调用
      • 当应用从后台返回到前台时,视图会出现 dsnt 被调用
      • applicationWillEnterForeground 也令人惊讶地不起作用。我正在使用这个: func applicationWillEnterForeground(application: UIApplication) { println("Hello again world") } 并且该函数永远不会触发,这很奇怪
      猜你喜欢
      • 2018-01-06
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 2015-08-19
      • 2019-02-08
      • 1970-01-01
      相关资源
      最近更新 更多