我有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)
}
答案 0 :(得分:0)
如果您告诉我们您收到错误的实际行,那将会很有帮助,但我假设它已经开启:
self.navigationController.pushViewController(view2, animated: true)
有三个原因可能会导致该行出错。当view2
期望它不属于nil
时,两者都与pushViewController
有关。
instantiateViewControllerWithIdentifier
返回nil
。然后view2
将为nil
,当pushViewController
尝试推送nil
时,您会收到错误ViewController2
类型。在这种情况下,使用as?
的转化将返回nil
,同时导致pushViewController
断言self.navigationController
为nil
。当您尝试在pushViewController
上致电nil
时,您会收到错误