【问题标题】:nil error when accessing IBOutlet connected to storyboard in viewDidLoad()在 viewDidLoad() 中访问连接到情节提要的 IBOutlet 时出现零错误
【发布时间】:2021-07-14 16:44:27
【问题描述】:

我正在尝试将标题添加到我的表格视图(而不是部分标题)。但是由于某些原因(我不知道它是什么),将一个 UIView 拖到表格视图然后运行应用程序后,标题仍然无法出现在我的应用程序中。

所以我尝试将它添加到我的代码中。问题来了,这个app运行后会停止并报一个致命错误:Fatal error: "Unexpectedly found nil while implicitly unwrapping an Optional value"。

我确信我在我的代码和情节提要之间建立了联系,因为我的 IBOutlet 旁边的圆圈是实心的,我可以在我的情节提要中看到这种联系。它在 viewDidLoad() 中,所以我认为视图已经加载?

Xcode 12.5,快速 5

我不知道为什么,有人可以帮助我吗?

p.s:我试过 clean 但没用。

p.p.s:对不起,我标记了一个错误的标志,与发生错误的位置相匹配。我已经在我的代码中更正了。谢谢你!

这是我的代码。

    import UIKit

class ItemsViewController: UITableViewController {
    
    @IBOutlet var addButton: UIButton!
    @IBOutlet var editButton: UIButton!
    @IBOutlet var headerView: UIView!
    
    @IBAction func addNewItem(_ sender: UIButton){
        
    }
    
    @IBAction func toggleEditingMode(_ sender: UIButton){
        // ...
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
       // ...
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        // ...
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.tableHeaderView = headerView 
headerView.backgroundColor = UIColor.red // error here
tableView.tableHeaderView?.addSubview(editButton) 
        tableView.tableHeaderView?.addSubview(addButton)
        tableView.tableHeaderView?.backgroundColor = UIColor.red
    }

}

【问题讨论】:

  • 'headerView'的类名真的是UIView吗?
  • 嗨@ElTomato,我想是的。如您所见,在代码中是UIView。在情节提要中,我只是将“视图”拖到表格视图中。所以我认为是。
  • 我不使用UITableViewController。因此,如果您愿意,请尝试以下操作,而不是“tableView.tableHeaderView = headerView”。让 myView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 30.0); myView.backgroundColor = UIColor.orange; tableView.tableHeaderView = myView
  • 其实可以尝试将headerView设置为viewWillAppearviewDidAppearviewDidLayoutSubviews()下的table view。
  • 如果我像你所说的'tableView.tableHeaderView = headerView'. let myView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: 30.0); myView.backgroundColor = UIColor.orange; 那样新建一个UIView,它确实有效!

标签: ios swift xcode


【解决方案1】:

如果您确定您已正确连接@IBOutlets,请确保您使用UIStoryboard.instantiateViewController(withIdentifier:) 来实例化您的视图控制器。

如果您不使用上述方法,您的故事板布局将不会链接到您的视图控制器实例。

【讨论】:

  • 我没有添加我的自定义 init()。这是否意味着我正在使用UIStoryboard.instantiateViewController(withIdentifier:) 来实例化我的视图控制器?
猜你喜欢
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
相关资源
最近更新 更多