美文网首页
NotificationCenter 通知Key的管理

NotificationCenter 通知Key的管理

作者: 啧啧同学 | 来源:发表于2020-08-05 11:44 被阅读0次

    通过Swift的extension, 可以很方便声明及管理NotificationCenter的key

    创建一个文件FCNotificationConst,专门用来存放NotificationCenter的key

    /* 登录相关变化等 */
    extension Notification.Name {
        
        static let login = NSNotification.Name("com.fc.login")
        static let offlineLogin = NSNotification.Name("com.fc.offline.login")
        static let logout = NSNotification.Name("com.fc.logout")  
        static let otherLogin = NSNotification.Name("com.fc.otherLogin")
        static let sessionExpired = NSNotification.Name("com.fc.sessionExpired")
    
    }
    
    /* 具体业务相关 */
    extension NSNotification.Name {
        // 切换语言
        static let langSwitched = NSNotification.Name("com.fc.lang.switched")
        //切换主题
        static let themeSwitched = NSNotification.Name("com.fc.theme.switched")
    }
    
    

    使用🌰

    
    //发送切换语言的通知
    NotificationCenter.default.post(name: .langSwitched, object: nil)
    //监听语言的通知
    NotificationCenter.default.addObserver(self, selector: #selector(onReceivedLangSwitchedNotification(_:)), name: .langSwitched, object: nil)
    
    @objc func onReceivedLangSwitchedNotification(_ note: Any) {
       /*   接受到语言变更通知后的操作 */
     }
    
    

    相关文章

      网友评论

          本文标题:NotificationCenter 通知Key的管理

          本文链接:https://www.haomeiwen.com/subject/ifmnrktx.html