Xareth
Xareth

Reputation: 23

(Swift) Table View Controller. cellForRowAt is not triggered

Problem: tableView Controller is not showing categoryArray items in table.

Diagnose:
- 1st tableView numberOfSections method is triggered and returns 1 (print(categoryArray.count)
- 2nd tableView cellForRowAt method never starts (print statement does not work)
- Table View Controller does not need delegate. However, I tried to add tableView.delegate = self
- x-code restart did not help

Question: Why the 2nd tableView method does not work and how to fix this?

import UIKit
import CoreData

class CategoryViewController: UITableViewController {

    var categoryArray = [Category]()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    override func viewDidLoad() {
        super.viewDidLoad()
        loadCategories()
    }

    // MARK: - TableView DataSource Methods

    override func numberOfSections(in tableView: UITableView) -> Int {
        return categoryArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("this should print")
        let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! CategoryCell

        let category = categoryArray[indexPath.row]
        cell.categoryNameTextField.text = category.name

        return cell
    }

Upvotes: 2

Views: 241

Answers (1)

vadian
vadian

Reputation: 285072

  1. Instead of numberOfSections implement numberOfRows

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categoryArray.count
    }
    
  2. At the end of viewDidLoad reload the table view

    override func viewDidLoad() {
        super.viewDidLoad()
        loadCategories()
        tableView.reloadData()
    }
    

    If loadCategories() contains something asynchronous reload the table view when the data are loaded.

Upvotes: 1

Related Questions