创建 viewcontroller 的实例并以编程方式对其进行 segue

Make instance of view controller and segue to it programatically

我的故事板中有两个视图控制器:view1view2

view1 中,我使用情节提要从它的 tableview 转到 view2

但现在在 view2 中,我以编程方式创建了一个按钮,它应该继续到另一个实例化的 view2

当按钮被点击时,我做了一个函数来执行:

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标识符。所以我想以某种方式做到这一点,但我真的找不到管理它的好方法。

有没有办法以编程方式创建 segue?我试图从情节提要中进行转场,但是由于按钮是通过编程方式创建的,所以我无法转场到 view2view2

您想使用 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)

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