Table 视图不显示数据,为什么? (Swift 3)

Table View doesn't show Data, why? (Swift 3)

我制作了一个使用 table 视图来保存数据的应用程序。 table 视图显示了通过 UserDefaults 保存的数组的元素。由于 TableViewControllers 看起来有点丑,我做了一些不同的事情:我把一个 TableView 变成了一个普通的 ViewController。 我的问题是:尽管我尽我所能让 TableView 显示数据,但它没有,我也不知道为什么。谁能帮帮我? 这是 ViewController:

的代码
class ErfolgreicheChallenges: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!

    var data = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        myTableView.delegate = self

        data.append("test")
        data.append("lol")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        myTableView.dataSource = self

        let cell = myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel!.text = data[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }

}

感谢大家的观看!祝你有美好的一天

您需要在 viewDidLoad 或类似的地方设置数据源和数据委托。

您正在 cellForRowAt 中设置数据源,但永远不会调用它!

替换viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()

    myTableView.dataSource = self
    myTableView.delegate = self

    data.append("test")
    data.append("lol")
    myTableView.reloadData()

}

并将 numberOfRowsInSection 替换为

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

并删除 cellForRow 中的 myTableView.dataSource = self

如果代码崩溃,则 myTableView 未在 IB 中连接。

如评论中所述,考虑使用 UITableViewController,它有一个 table 带有预连接数据源和委托的视图实例。