找到零展开可选表视图swift

找到零展开可选表视图swift,swift,uitableview,Swift,Uitableview,我有一个错误: "Unexpectedly found nil while implicitly unwrapping an Optional value" for cartTableView.register(nib, forCellReuseIdentifier: "CartTableViewCell") 这是我的密码。我正在为这个视图控制器使用一个故事板,为单元格使用一个.xib文件 class CartViewController: UIView

我有一个错误:

"Unexpectedly found nil while implicitly unwrapping an Optional value"
for cartTableView.register(nib, forCellReuseIdentifier: "CartTableViewCell")
这是我的密码。我正在为这个视图控制器使用一个故事板,为单元格使用一个.xib文件

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
    }
我来自编程表视图。这是怎么回事

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


他现在正在工作。我的代码是从另一个函数运行的,这就是为什么不工作的原因。这是正确的代码。

cartTableView
为零。您在故事板中正确连接了吗?@Larme是的,已连接..UINib(nibName:“CartTableViewCell”,bundle:nil)-如果bundle中没有具有该名称的nib文件,则为nil是
cartTableView
nil?如果你在那行之前打印(cartTableView)它会崩溃吗?嗯,打印为零,但在同一行崩溃。不知道为什么是零,我已经连接了它。我已经用TableViewCell.xib更新了帖子
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)
}