Swift 學習之 NotificationCenter


1、發布新通知:

NotificationCenter.default.post(name:  NSNotification.Name(rawValue: "MessageMainCount"), object: nil, userInfo: ["count":"\(count)"])

 2、接受新通知

NotificationCenter.default.addObserver(self, selector: #selector(self.changeBadgeValue(notification:)), name: NSNotification.Name(rawValue: "MessageMainCount"), object: nil)

 3、設置接受通知的監聽方法

func changeBadgeValue(notification: Notification) -> Void {
        
        let name = notification.name
        let userInfo = notification.userInfo as! [String:Any]
        let userInfoDic = userInfo as NSDictionary
        
        if name == NSNotification.Name(rawValue: "MessageMainCount"){
 
            let badgeValue: String = userInfoDic.object(forKey: "count") as! String
           
            self.messageVC.parent?.tabBarItem.badgeValue = badgeValue
        }
}

 4、移除通知監聽

deinit{
        NotificationCenter.default.removeObserver(self)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM