0

I have mainViewController and inside have scrollView and I have secondViewController I want to change scrollView offset to top from secondViewController when I want to try it with NSNotificationCenter gives me ;

: unrecognized selector sent to instance 0x7ff83e024200'

How can I fix it ? My codes under below.

mainViewController

       override func viewDidLoad() {
            super.viewDidLoad()

            NotificationCenter.default.addObserver(self, selector: "gotop:", name: NSNotification.Name(rawValue: "gotop"), object: nil)

    }

  func gotop(){
         scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
    }

secondViewController

@IBAction func goButton (sender : UIButton){

        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "gotop"), object: nil)


    }
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85

3 Answers3

2

I have used below code in my project to add notification :

NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.gotop), name: NSNotification.Name(rawValue: "gotop"), object: nil)

Try if it works in your scenario.

Amit
  • 4,837
  • 5
  • 31
  • 46
2

check your addObserver code, selector should have below signature

NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.goTop(notification:)), name: Notification.Name("gotop"), object: nil)

Method handler for received Notification:

func goTop(notification: Notification){
   scrollView.setContentOffset(CGPoint(x:0, y:0), animated: false)
}

For posting notification

NotificationCenter.default.post(name: Notification.Name("gotop"), object: nil)

Remove Notification in denit

deinit {
  NotificationCenter.default.removeObserver((self, name: Notification.Name("gotop"), object: nil)
}
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
1

the definition of your "goTop" func is wrong :

instead of

func gotop(){
  //do your stuff
}

try this :

func gotop(notification : NSNotification){
   //do your stuff
}

let me know if this solve your problem.

Leonardo
  • 218
  • 4
  • 17