简体   繁体   中英

Notification observer selector not called

I have this observer

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(GetUserID(_:)), name: Notification.Name("UserID"), object: nil)
    }

and this selector function

    @objc func GetUserID(_ notification: Notification){
        let User = notification.object as? String
        self.UserID = User
    }

And I keep getting nil in UserID even though I am certain that when I get the notification it is not nil which makes me believe that the selector is not being called

You can get observer value by below method

 let selectedIndex:[String: Int] = ["selectedIndex": 1]
                         //selectedindex = 0
                         // post a notification
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SelectedSegment"), object: nil, userInfo: selectedIndex)



    NotificationCenter.default.addObserver(self, selector: #selector(self.changeSegmentControlIndex(notification:)), name: Notification.Name("SelectedSegment"), object: nil)

     @objc func changeSegmentControlIndex(notification: Notification) {
        
        if let selectedIndex = notification.userInfo?["selectedIndex"] as? Int {
         // do something with your image
            print(selectedIndex)

         }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM