如何在Swift 4中从自定义类导航到UIViewController

时间:2018-03-15 14:13:02

标签: ios swift uinavigationcontroller swift4

我有一个ViewController,它有一个按钮,它在MyClass.swift中调用一些方法。当我按下那个按钮时,我正试图从MyClass.swift导航到UIViewController MainViewController。我实现了这个方法,我在日志中“导航......”但没有任何反应。

class Myclass {
// some code ...
func someFunc() {

    // some code ...
    navigateToMainViewController()

}

func navigateToMainViewController() {
    let storyboard: UIStoryboard? = UIApplication.shared.keyWindow?.rootViewController?.storyboard
    if let myMVC = storyboard?.instantiateViewController(withIdentifier: "MainViewController") {
        print("navigating....")
        let navController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
        navController?.pushViewController(myMVC, animated: true)
    }else {
        print("Something wrong..")
    }
}

// some code ...
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

更改导航功能并向其添加viewController参数,并在myClass中输入 UIViewController 类型的变量:

var viewController: UIViewController!


func someFunc(_ viewController: UIViewController) {
    self.viewController = viewController
    self.navigateToMainViewController()
}

func navigateToMainViewController() {
  let storyboard: UIStoryboard? = UIApplication.shared.keyWindow?.rootViewController?.storyboard
  if let myMVC = storyboard?.instantiateViewController(withIdentifier: "MainViewController") {
      print("navigating....")

      self.viewController.navigationController?.pushViewController(myMVC, animated: true)
  }else {
      print("Something wrong..")
  }
}

然后从viewController,使用ViewController的实例调用 someFunc()

class ViewController: UIViewController {
    @IBAction func buttonPressed(_ sender: UIButton) {
          myClassObject.someFunc(self)
    }
}