【问题标题】:How to know when View will become active from background如何知道 View 何时从后台变为活动状态
【发布时间】:2015-01-12 21:31:59
【问题描述】:

是否没有类似于applicationDidBecomeActive 的方法,但它适用于视图控制器。我知道viewWillAppearviewDidAppear,它们在您导航到此视图控制器时起作用,但我需要在用户离开应用程序(通过按主页按钮)然后重新打开应用程序时调用的东西。我有一个在视图控制器的viewDidLoad 中定义的全局变量,但在applicationDidBecomeActive 方法中重新定义。这意味着如果应用程序进入后台,然后回到前台,变量将会改变。我需要用类似viewDidBecomeActive 的方法重置它。

【问题讨论】:

标签: ios swift methods


【解决方案1】:

你可以简单地注册你的视图控制器来监听 UIApplicationDidBecomeActiveNotification 通知。

在视图控制器的 viewWillAppear 方法中添加以下内容:

 [[NSNotificationCenter defaultCenter]addObserver:self
                                         selector:@selector(yourMethod)
                                             name:UIApplicationDidBecomeActiveNotification
                                           object:nil];

【讨论】:

  • 还有强制性的快速评论。 NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(Class.method), name: UIApplicationDidBecomeActiveNotification, object: nil)
【解决方案2】:

斯威夫特 5

    NotificationCenter.default.addObserver(
        self,
        selector:#selector(yourMethod),
        name: UIApplication.didBecomeActiveNotification,
        object: nil)

和你的功能

@objc func yourMethod() {
   // your code
}

【讨论】:

    【解决方案3】:

    斯威夫特 4

    NotificationCenter.default.addObserver(
        self,
        selector:#selector(refreshWhenAppBecomesActive),
        name: NSNotification.Name.UIApplicationDidBecomeActive,
        object: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2015-05-19
      相关资源
      最近更新 更多