首页 > 解决方案 > 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)
    }

Cell

标签: swiftuitableview

解决方案


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

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


推荐阅读