从另一个控制器加载视图控制器

时间:2017-03-10 09:06:28

标签: ios swift controller

我正在使用此代码在ViewController中的容器内加载视图控制器,而不使用任何segue。 示例:

let newViewController =self.storyboard?.instantiateViewController(withIdentifier: "FBViewController")
            newViewController!.view.translatesAutoresizingMaskIntoConstraints = false
            self.cycleFromViewController(oldViewController: self.currentViewController!, toViewController: newViewController!)
            self.currentViewController = newViewController

此代码适用于任何控制器,但在一种情况下,我需要加载一个名为FBViewController的控制器,并在其ViewDidLoad中检查用户是否已记录,以防他想要立即加载另一个控制器而不是FBViewController。 我在FBViewController的viewDidLoad中尝试了这段代码:

   let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "userProfilePage")
            self.present(controller, animated: true, completion: nil)

我尝试在主视图控制器中调用一个方法来加载想要的视图:

 let otherViewController: ViewController = ViewController()
            otherViewController.loggedIn()

方法:

func loggedIn(){
    let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "userProfilePage")
    newViewController!.view.translatesAutoresizingMaskIntoConstraints = false
    self.cycleFromViewController(oldViewController: self.currentViewController!, toViewController: newViewController!)
    self.currentViewController = newViewController
}

他们都没有奏效。我感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以在MainViewController中尝试以下内容:

var newViewController : UIViewController
if loggedIn == true {
    newViewController = self.storyboard?.instantiateViewController(withIdentifier: "userProfilePage")
} else {
    newViewController = self.storyboard?.instantiateViewController(withIdentifier: "FBViewController")
}

newViewController!.view.translatesAutoresizingMaskIntoConstraints = false
self.cycleFromViewController(oldViewController: self.currentViewController!, toViewController: newViewController!)
self.currentViewController = newViewController

答案 1 :(得分:0)

您拥有的代码应该可以使用,只需转到故事板并选择要呼叫的控制器即可。然后确保在故事板ID下,您使用与调用它相同的名称。