XIB 文件中的 TableView 导致错误

TableView in XIB file causing errors

我正在尝试在 XIB 文件中添加 tableView,但出现此错误:this class is not key value coding-compliant for the key tableView.。我以前从未使用过 XIB 文件,所以我不确定问题出在哪里

这是我加载 XIB 的方式:

let scoresVC = UIViewController(nibName: "LiveScoresViewController", bundle: nil)
navigationController?.pushViewController(scoresVC, animated: true)

class LiveScoresViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
    
    @IBOutlet weak var tableView: UITableView!

    

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UINib(nibName: "LiveScoreCell", bundle: nil), forCellReuseIdentifier: "LiveScoreCell")
    }
}

问题是let scoresVC = UIViewController(nibName: "LiveScoresViewController", bundle: nil)这一行。您需要这样更改:

let scoresVC = LiveScoresViewController(nibName: "LiveScoresViewController", bundle: nil)

您正在创建一个普通的 UIViewController 并告诉它从 LiveScoresViewController.xib 加载视图。您需要创建 LiveScoresViewController 的实例。这应该有效:

let scoresVC = LiveScoresViewController()

该对象将使用它自己的 class 名称来查找 xib。