Swift 来自不同 Storyboard 的 PushViewController

Swift PushViewController From A Different Storyboard


我正在尝试以编程方式显示我的 ViewControllers 另一个故事板之一。但由于某些原因,我试图显示的 ViewController 的属性为零。

那是我的错误:Unexpectedly found nil while unwrapping an Optional value

I'm getting the error in my SecondViewController. It is showing but my app crashes due to the properties being nil.

这是我的代码:

let secondStoryBoard = UIStoryboard(name: "SecondStoryBoard", bundle: nil)
let secondViewController = secondStoryBoard.instantiateViewController(withIdentifier: "secondVC") as! SecondVC


self.navigationController?.pushViewController(secondViewController, animated: true)

这是产生错误的代码:

class SecondVC: ViewController
{
    @IBOutlet weak var mapView: MKMapView!
    mapView.isHidden = true // ERROR!! Unexpectedly found nil while unwrapping an Optional value
}

SOLVED: just had to reconnect my @IBOutlet connections

这意味着下一行是 nil 或不是 SecondVC.

类型
secondStoryBoard.instantiateViewController(withIdentifier: "secondVC")

我会在你的情节提要中验证你有一个标识符 secondVC 并且视图控制器的类型是 SecondVC.


编辑:

根据 OP 在问题中发布的新代码,将 SecondVC 更改为以下内容应该可行。

class SecondVC: ViewController
{
    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad() {
        mapView.isHidden = true
    }
}

基本上,这将等到视图加载后再访问 mapView。对于原始代码,您试图在实际加载之前访问 mapView


编辑 2:

看起来 mapView outlet 没有正确链接到故事板。