Medium - iOS; Implementing the Notification/Observer Communication Pattern

원문 - Moussa Hellal

Trend 파악을 Medium 기고문 요약 포스팅 - iOS에서 노티/옵저버 커뮤니케이션 패턴 구현하기

Photo by Dennis Brendel on Unsplash

let addItemNotfication = NSNotification.Name(rawValue: "addItem")
func createObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(TabBarController.setBadge(notification:)), name: addItemNotfication, object: nil)
}

@objc func setBadge(notification: NSNotification) {
        //get the existant badge value
        let badgeValue = Int(self.tabBar.items![0].badgeValue!)!
        // set the new badge value
        self.tabBar.items![0].badgeValue = "\(badgeValue + 1)"
}
override func viewDidLoad() {
        super.viewDidLoad()
        // add badge to my cart tab icon with value of zero
        self.tabBar.items![0].badgeValue = "0"
        createObservers()
}
import UIKit

class TabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // add badge to my cart tab icon with value of zero
        self.tabBar.items![0].badgeValue = "0"
        createObservers()
    }

    func createObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(TabBarController.setBadge(notification:)), name: addItemNotfication, object: nil)
    }

    @objc func setBadge(notification: NSNotification) {
        //get the existant badge value
        let badgeValue = Int(self.tabBar.items![0].badgeValue!)!
        // set the new badge value
        self.tabBar.items![0].badgeValue = "\(badgeValue + 1)"
    }
}
NotificationCenter.default.post(name: addItemNotfication, object: nil,userInfo: nil)

Summary


© 2019. All rights reserved.

Powered by Hydejack v8.1.1