当我尝试访问它们时,IBOutlet变量返回nil。错误:线程1:致命错误:在展开可选值时意外发现nil

时间:2019-04-05 13:49:21

标签: ios swift storyboard mkmapview mapbox

我有一个实现UIViewController的{​​{1}}。我正在尝试在导航栏的顶部放置两个按钮。

我无法看到按钮或导航栏,因此我尝试按照this post的建议在MGLMapViewDelegate中使用函数view.bringSubviewToFront()

这样做时,我收到了错误

  

错误:线程1:致命错误:展开一个可选值时意外发现nil

我不知道viewDidLoadFunction()变量怎么可能为零,我认为它们已分配给情节提要按钮


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

IBOutlet

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

enter image description here enter image description here enter image description here enter image description here enter image description here

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

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)
  }
}

我尝试将视图移到mapview的前面,而不是主视图

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

I've tried placing the code inside functions like awakeFromNib and viewDidLayoutSubviews

self.mapView.bringViewToFront(navBar)

1 个答案:

答案 0 :(得分:2)

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

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)
   }