使用 NotificationCenter 訂閱各種事件

1 篇文章 / 0 new
author
使用 NotificationCenter 訂閱各種事件
► 訂閱 Application 事件
override func viewDidLoad() {
    super.viewDidLoad()
    //監聽Application事件
    NotificationCenter.default.addObserver(self, selector: #selector(eventNotification(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil);   
}
//取消監聽
deinit {
    NotificationCenter.default.removeObserver(self);
}
func eventNotification(_ notification: NSNotification){
    switch notification.name {
    case NSNotification.Name.UIApplicationWillEnterForeground:
        //...
        break;
    default:
        break;
    }
}

支援事件
UIApplicationDidFinishLaunching
UIApplicationWillEnterForeground
UIApplicationDidEnterBackground
UIApplicationWillResignActive
UIApplicationDidBecomeActive
UIApplicationDidReceiveMemoryWarning
UIApplicationWillTerminate
UIApplicationSignificantTimeChange
UIApplicationWillChangeStatusBarOrientation
UIApplicationDidChangeStatusBarOrientation
UIApplicationWillChangeStatusBarFrame
UIApplicationDidChangeStatusBarFrame
UIApplicationBackgroundRefreshStatusDidChange

► 鍵盤事件
NSNotification.Name.UIKeyboardWillShow
NSNotification.Name.UIKeyboardWillHide
Free Web Hosting