Call function from other ViewController

前端 未结 4 1668
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2021-01-24 15:57

    Try this:

    SecondViewController().showAlert(self)
    

    In your second view controller

     if let text = textField?.text {
         dispatch_async(dispatch_get_main_queue(),{
    
          let alert = UIAlertView(title: "Working!", message: "This function was called from FirstViewController!\nTextField says: \(text)", delegate: nil, cancelButtonTitle: "Okay")
          alert.show()
    
        })
    }
    
    0 讨论(0)
  • If you want to show alert view to second viewcontroller from firstview controller when go to it you can do something like,

      self.performSegueWithIdentifier("your segue identifier", sender: self)  // or whatever way if you are not using storyboard or segue
    
        let alert = UIAlertView(title: "Working!", message: "This function was called from FirstViewController!", delegate: nil, cancelButtonTitle: "Okay")
        alert.show()
    

    If you want to set any variables of secondviewcontroller then you need to implement prepareForSegue method. (if you are using segue).

    Second thing you can show alertview in viewDidload of secondViewController also.

    0 讨论(0)
  • 2021-01-24 16:10

    EDIT: These functions have been revised in swift 3 as follows:

    Code in FirstViewController

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

    Code in SecondViewController:

    @IBAction func callFunctionInOtherClass(sender: AnyObject) {
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "showAlert"), object: nil)
    }
    
    0 讨论(0)
提交回复
热议问题