在swift中从一个视图转到另一个视图

时间:2014-07-26 04:46:39

标签: uiviewcontroller swift

我有2个按钮,应该在视图controller1和视图controller2之间切换。当我点击我的按钮切换到第二个视图控制器时,我不断收到错误:致命错误:无法打开Optional.None

var settings : UIButton = UIButton(frame: CGRectMake(0, 0, 40, 40))

    settings.setTitle("S", forState: UIControlState.Normal)
    settings.backgroundColor = UIColor.blackColor()
    settings.center = (CGPointMake(120, 30))
    settings.layer.cornerRadius = 8
    settings.addTarget(self, action: "settingsBar:", forControlEvents:UIControlEvents.TouchUpInside)
    settings.layer.borderWidth = 3
    settings.layer.borderColor = UIColor.grayColor().CGColor
    view.addSubview(settings)

@IBAction func settingsBar(sender: AnyObject){

    let view2 = self.storyboard.instantiateViewControllerWithIdentifier("view2") as?
        ViewController2
    self.navigationController.pushViewController(view2, animated: true)
}

1 个答案:

答案 0 :(得分:0)

如果您告诉我们您收到错误的实际行,那将会很有帮助,但我假设它已经开启:

self.navigationController.pushViewController(view2, animated: true)

有三个原因可能会导致该行出错。当view2期望它不属于nil时,两者都与pushViewController有关。

  1. 您的故事板中没有名为“view2”的视图控制器:这会导致instantiateViewControllerWithIdentifier返回nil。然后view2将为nil,当pushViewController尝试推送nil时,您会收到错误
  2. 名为“view2”的视图控制器不属于ViewController2类型。在这种情况下,使用as?的转化将返回nil,同时导致pushViewController断言
  3. 您的视图控制器(问题中的代码来自的视图控制器)实际上并未嵌入导航控制器中。这将导致self.navigationControllernil。当您尝试在pushViewController上致电nil时,您会收到错误