代码创建的segue如何绑定到viewController?

viewDidLoad: 方法里面创建了一个 segue

let aSegue = UIStoryboardSegue(identifier: "hello", source: self, destination: ViewControlerrB())

但是直接

performSegueWithIdentifier("hello", sender: self)

是找不到 segue “hello”
所以我的问题就是 怎么将创建的这个segue 绑定给某个变量从而使用?
storyBoard 中创建的方法不算

阅读 6.4k
4 个回答

如果prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)里没有做判断肯定是找不到segue "hello" 的。

你不能自己创建 segue ,只能在 storyboard 中连线并指定 identifier

我仔细的看了文档并且试了下
只有在重写了 perform:_ 方法或者用带perform:_ 方法的闭包的便利构造器才可以通过identifier 来访问 segue
也就是说只有在实现了上述方法segue才会被真正完全示例化来使用

两种方法:
1.写一个UIStoryboardSegue的子类,然后重写其 perform 方法.
2.使用

convenience init(identifier identifier: String?,
          source source: UIViewController,
     destination destination: UIViewController,
  performHandler performHandler: () -> Void)

方法来创建 UIStoryboardSegue.

一个 obj-c的示例如下:

    UIViewController * toVC = [[UIViewController alloc] init];
    
    
    UIStoryboardSegue * segue = [UIStoryboardSegue segueWithIdentifier:@"hello" source:self destination:toVC performHandler:^{
        [self presentViewController: toVC animated: YES completion: NULL];
    }];
    
    [segue perform];

另外,既然用纯代码了,或许不使用 segue,直接跳转,会更方便些.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题