Call function from other ViewController

前端 未结 4 1728
深忆病人
深忆病人 2021-01-24 15:31

I have two ViewControllers, FirstViewController and SecondViewController. Both have an own Swift file, FirstViewController.swift and

4条回答
  •  遇见更好的自我
    2021-01-24 15:47

    You may use NSNotificationCentre to accomplish this task.

    In viewDidLoad method of your SecondViewController class register self as observer to receive notification broadcasts:-

    override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(showAlert), name: NSNotification.Name(rawValue: "callForAlert"), object: nil)
    }
    

    and in FirstViewController's button action method you should fire the notification by writing :-

    @IBAction func callFunctionInOtherClass(sender: AnyObject) {
        //Call "func showAlert" in SecondViewController when clicking the UIButton in FirstViewController
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "callForAlert"), object: nil)
    }
    

    Don't forget to call removeObserver in SecondViewController's viewDidUnload method.

提交回复
热议问题