代码之家  ›  专栏  ›  技术社区  ›  hikki

创建视图控制器的实例并以编程方式对其进行分段

  •  1
  • hikki  · 技术社区  · 9 年前

    我的故事板中有两个视图控制器: view1 view2 .

    在里面 视图1 ,我用故事板从它的桌面视图到 视图2 .

    但现在在 视图2 ,我以编程方式创建了一个按钮,它应该被分段到另一个实例化的 视图2 .

    单击按钮时,我创建了一个要执行的函数:

    func buttonPressed(sender: UIButton){
      //TODO:- GET NEXT PAGE
      self.performSegueWithIdentifier("anotherView2", sender: sender)
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
      if(segue.identifier == "anotherView2"){
        let anotherView2Controller = segue.destinationViewController as! View2
        ...
        ...
      }
    }
    

    当然它不起作用,因为没有调用段标识符 anotherView2 所以我想设法做到,但我真的找不到好的方法来处理这件事。

    是否仍要以编程方式创建segue?我试图从情节提要中进行分段,但由于按钮是以编程方式创建的,我无法分段到 视图2 视图2 .

    1 回复  |  直到 9 年前
        1
  •  2
  •   Wyetro    9 年前

    你想用 presentViewController 而不是 performSegue :

    // however you want to initialize the new vc
    let vc2 : View2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("view2.id") as! View2
    

    初始化vc的另一种方法是:

    let vc2 = View2()
    

    然后设置数据并显示:

    vc2.index = index // whatever you want to pass
    self.presentViewController(vc2, animated: true, completion: nil)
    

    否则,您可以在故事板中创建一个新的视图控制器,但我不建议这样做。