Search code examples
swiftselectoraddobserver

How to pass parameter to selector in swift?


func addObserver(_ scrollView: UIScrollView) {
  NotificationCenter.default.addObserver(self, selector: #selector(XXX), name:, object:)
}

@objc func getScrollView (_ notification: Notification, useScrollView : UIScrollView) {
 // Doing something for scrollView
 
}

I want to pass the scrollView to the objc function getScrollView when I call addObserver function. How should I modify those two functions?


Solution

  • It is simpler to use block, like

    private var _observer: Any!  // unsubscribed automatically on deinit
    
    func addObserver(_ scrollView: UIScrollView) {
        _observer = NotificationCenter.default.addObserver(forName: name, 
                    object: nil, queue: nil) { notification in
            // ... just use scrollView here
        }
    }