2015-07-13 32 views

回答

7
在viewDidLoad中()UIViewController類內

,添加

// Add UIApplicationWillResignActiveNotification observer 
    NSNotificationCenter.defaultCenter().addObserver(
     self, 
     selector: "resigningActive", 
     name: UIApplicationWillResignActiveNotification, 
     object: nil 
    ) 
    NSNotificationCenter.defaultCenter().addObserver(
     self, 
     selector: "becomeActive", 
     name: UIApplicationDidBecomeActiveNotification, 
     object: nil 
    ) 

爲夫特4的iOS 11,使用:

NotificationCenter.default.addObserver(
    self, 
    selector: #selector(ViewController.resigningActive), 
    name: NSNotification.Name.UIApplicationWillResignActive, 
    object: nil) 

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

這兩個函數最後添加到視圖控制器:

@objc fileprivate func resigningActive() { 
    print("== resigningActive ==") 
} 

@objc fileprivate func becomeActive() { 
    print("== becomeActive ==") 
}