Search code examples
iosobjective-cuitableviewswift3userdefaults

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


I've made an app using a table view to persist data. The table view shows the elements of an array which is saved through UserDefaults. Since TableViewControllers look kind of ugly, I did it a bit different: I put a TableView into a normal ViewController. My problem is: even though I did everything I could to get the TableView to show the data, it doesn't, and I don't know why. Could anyone help me? Here's the code of the 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) {

    }

}

Thanks to everyone for having a look! Have a great day


Solution

  • Replace viewDidLoad with

    override func viewDidLoad() {
        super.viewDidLoad()
    
        myTableView.dataSource = self
        myTableView.delegate = self
    
        data.append("test")
        data.append("lol")
        myTableView.reloadData()
    
    }
    

    and replace numberOfRowsInSection with

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

    and delete myTableView.dataSource = self in cellForRow.

    If the code is crashing then myTableView is not connected in IB.

    As mentioned in the comments, consider to use UITableViewController which got a table view instance with pre-connected data source and delegate.