更好地使用UIApplicationWillResignActive
并且UIApplicationDidBecomeActive
由于它们捕获“顶部矩形捕获和释放事件”。我建议使用这个根类:
class VBase: UIViewController {
fileprivate var listenersActivated = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onStart()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
onStop()
removeListeners()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
onStop()
removeListeners()
}
internal func iniListeners() {
if (!listenersActivated) {
NotificationCenter.default.addObserver(self, selector: #selector(onStop), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onStart), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
listenersActivated = true
} else {
}
}
internal func removeListeners() {
NotificationCenter.default.removeObserver(self)
listenersActivated = false
}
internal func onStop() {
}
internal func onStart() {
iniListeners()
}
}
覆盖onStop()
和onStart()
内部子项以捕获所有视图出现/消失
那是,
class SomeViewController: VBase {
...
override func onStart() {
super.onStart()
someFunctionToInitialize()
}
override func onStop() {
super.onStop()
stopTimer()
someFunctionToDesctruction()
}
}