swift - Found nil unwrapping optional table view swift
问题描述
I've got an error:
"Unexpectedly found nil while implicitly unwrapping an Optional value"
for cartTableView.register(nib, forCellReuseIdentifier: "CartTableViewCell")
This is my code. I'm using a storyboard for this view controller and a .xib file for the cell.
class CartViewController: UIViewController {
@IBOutlet weak var cartTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "CartTableViewCell", bundle: nil)
// error is below
cartTableView.register(nib, forCellReuseIdentifier: "CartTableViewCell")
cartTableView.delegate = self
cartTableView.dataSource = self
}
}
extension CartViewController: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = cartTableView.dequeueReusableCell(withIdentifier: "CartTableViewCell", for: indexPath) as! CartTableViewCell
return cell
}
I'm coming from a programmatic table view. This is how
@IBAction func addButtonPressed(_ sender: UIButton) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let cartVC = storyBoard.instantiateViewController(withIdentifier: "CartVC") as! CartViewController
self.present(cartVC, animated: true, completion: nil)
}
解决方案
let rightButton = UIBarButtonItem(image: UIImage(systemName: "cart"), style: .plain, target: self, action: #selector(rightButtonPressed(sender:)))
navigationItem.rightBarButtonItems = [rightButton]
@objc func rightButtonPressed(sender: UIBarButtonItem) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let cartVC = storyBoard.instantiateViewController(withIdentifier: "CartVC") as! CartViewController
self.present(cartVC, animated: true, completion: nil)
}
现在正在工作。我的代码是从另一个函数运行的,这就是为什么不起作用。这是正确的代码。
推荐阅读
- spring - 运行 KafkaEmbedded 进行单元测试时出现 java.lang.NoClassDefFoundError
- node.js - 将 Node.js 应用程序上传到 WinSCP 服务器
- sql - 使用 group by 子句从具有最大值的行中获取另一个值
- javascript - firebase node js TypeError:无法读取导出时未定义的属性“toId”
- python - 如何使用pandas groupby对一些行降序和一些行升序排序
- reactjs - 对象作为反应子无效(react-native)
- interrupt - STM32 SPI在使用中断时丢弃数据
- php - 在woocommerce中将任何产品添加到购物车后,如何立即删除客户端浏览器上的“PHPSESSID”cookie?
- swift - Swift 和 Cloud Firestore 事务 - getDocuments?
- java - Hibernate Envers - 请求更改对象列表