fatal error: unexpectedly found nil while unwrapping an Optional value (EXC_BAD_INSTRUCTION)

fatal error: unexpectedly found nil while unwrapping an Optional value (EXC_BAD_INSTRUCTION)

我发现了许多类似的问题,但 none 对我有所帮助。当我显示一个名为 TestVCViewController 的视图控制器并使用此处声明的 IBOutlet UILabel 执行某些操作时,我收到此错误。

我检查了 IBOutlet 连接,它已连接。

如果我只是简单地显示 VC(即 IBOutlet 已声明并已连接但未被使用),则没有错误,但是,视图并未像显示的那样加载黑色,而实际上它有白色背景。

我检查了这个答案 并给出了 UILabel 所有尺寸的自动布局约束 类 但它没有帮助。

FirstVC.swift:

var nextVC:TestVCViewController
required init(coder aDecoder: NSCoder) {
    nextVC = TestVCViewController()
    super.init(coder: aDecoder)
}

按钮操作:

self.nextVC =  TestVCViewController()
self.presentViewController(self.nextVC, animated: true, completion: nil)

TestVCViewController.swift:

class TestVCViewController: UIViewController {

@IBOutlet  var screwManLABEL: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    screwManLABEL.text = "heyyyy"
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

我在 screwManLABEL.text = "heyyyy" 处遇到异常,调试器显示

fatal error: unexpectedly found nil....

更改初始化方式TestVCViewController

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("your_VC_ID") as! TestVCViewController
self.presentViewController(vc, animated: true, completion: nil)