3 回答
TA贡献1946条经验 获得超3个赞
应用程序中的任何类都可以成为应用程序中不同通知的“观察者”。创建(或加载)视图控制器时,您需要将其注册为观察者,UIApplicationDidBecomeActiveNotification并指定在将通知发送到应用程序时要调用的方法。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification object:nil];
不要忘记自己清理!当您的视图消失时,请记住将自己移除为观察者:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidBecomeActiveNotification
object:nil];
有关通知中心的更多信息。
TA贡献1895条经验 获得超7个赞
Swift 3,4等效:
添加观察者
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
object: nil)
删除观察者
NotificationCenter.default.removeObserver(self,
name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
object: nil)
打回来
@objc func applicationDidBecomeActive() {
// handle event
}
TA贡献1856条经验 获得超17个赞
Swift 2等效:
let notificationCenter = NSNotificationCenter.defaultCenter()
// Add observer:
notificationCenter.addObserver(self,
selector:Selector("applicationWillResignActiveNotification"),
name:UIApplicationWillResignActiveNotification,
object:nil)
// Remove observer:
notificationCenter.removeObserver(self,
name:UIApplicationWillResignActiveNotification,
object:nil)
// Remove all observer for all notifications:
notificationCenter.removeObserver(self)
// Callback:
func applicationWillResignActiveNotification() {
// Handle application will resign notification event.
}
- 3 回答
- 0 关注
- 1121 浏览
添加回答
举报