【发布时间】: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设置为
viewWillAppear、viewDidAppear或viewDidLayoutSubviews()下的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,它确实有效!