IBOutlet variables return nil when I try to access them. Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

IBOutlet variables return nil when I try to access them. Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我有一个 UIViewController 实现了 MGLMapViewDelegate。我试图在顶部放置一个带有两个按钮的导航栏。

我无法让我的按钮或导航栏可见,所以我尝试按照

上的建议在 viewDidLoadFunction() 中使用函数 view.bringSubviewToFront()

当我这样做时,我收到错误

Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我不明白 IBOutlet 变量怎么会是 nil,我以为它们被分配给故事板按钮


我的ViewControllerClass(至少我认为重要的部分)

class ViewController: UIViewController, MGLMapViewDelegate {

...

var mapView: MGLMapView?
@IBOutlet var navBar: UINavigationBar!
@IBOutlet var signOutButton: UIButton!
@IBOutlet var newPostButton: UIButton!

...

override func viewDidLoad() {
            super.viewDidLoad()

    self.mapView = MGLMapView(frame: view.bounds, styleURL: MGLStyle.lightStyleURL)

    ...

        view.addSubview(self.mapView!)

        view.addSubview(navBar)
        view.addSubview(signOutButton)
        view.addSubview(newPostButton)
        //Make the navBar and Buttons visible
        view.bringSubviewToFront(self.navBar)
        view.bringSubviewToFront(self.signOutButton)
        view.bringSubviewToFront(self.newPostButton)

        ...
}

...

@objc func handleLogout() {
     let loginController = SignInViewController()

     do {
          try Auth.auth().signOut()
      } catch let logoutError {
          print(logoutError)
      }

      present(loginController, animated: true, completion: nil)
  }
}

一些我认为可能很重要的故事板截图

I've tried placing this in my view controller right after super.viewDidLoad()

self.storyboard?.instantiateViewController(withIdentifier: "mainViewController") as! ViewController

我试过将视图放在地图视图的前面而不是主视图

self.mapView.bringViewToFront(navBar)

    override func awakeFromNib() {
        super.awakeFromNib()

        //Make the navBar and Buttons visible
        self.mapView!.bringSubviewToFront(self.navBar)
        self.mapView!.bringSubviewToFront(self.signOutButton)
        self.mapView!.bringSubviewToFront(self.newPostButton)

    }

根据您的评论,我了解到您错误地实例化了控制器。

let mainController = ViewController(). // Wrong

这只会实例化 ViewController 而不是故事板中的任何对象。

使用下面的代码从情节提要中实例化 viewcontroller。

    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainViewController") as? ViewController {
        //Set any data if required, then present
        self.present(vc, animated: true, completion: nil)
    }

如果您使用多个故事板,

 let storyboard = UIStoryboard(name: "Main", bundle: nil)
 if let vc = storyboard.instantiateViewController(withIdentifier: "mainViewController") as? ViewController {
        self.present(vc, animated: true, completion: nil)
   }