CPL
CPL

Reputation: 25

cellForRowAtIndexPath for TableView not being called?

I'm trying to build a simple TableView in Swift, but instead of conforming to the datasource protocol within my ViewController, I wanted to create a new class that will serve as the DataSource. Unfortunately, with this approach, I'm not able to get anything to load in my ViewController.

This is my ViewController Class:

class SaladViewController: UIViewController {

    @IBOutlet weak var saladTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let tableData = LunchTableData()
        self.saladTable.dataSource = tableData
    }

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

And this is my DataSource class:

class LunchTableData: NSObject, UITableViewDataSource {

    var things = ["One", "Two", "Three"]

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")

        let itemText = cell!.viewWithTag(100) as! UILabel
        itemText.text = things[indexPath.row]

        return cell!
    }
}

RowAtIndexPath is getting called fine, so I'm just not sure why CellForRowAtIndexPath isn't ever being called. I've set a breakpoint and it never hits it.

Thank you for the help!

Upvotes: 0

Views: 548

Answers (1)

Alex
Alex

Reputation: 616

I think tableData is destroyed after viewDidLoad() is finished.

So move the following line just below the @IBOutlet weak var saladTable: UITableView! line.

let tableData = LunchTableData()

Hope this help you

So full code

class SaladViewController: UIViewController {

    @IBOutlet weak var saladTable: UITableView!

    let tableData = LunchTableData()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.saladTable.dataSource = tableData
    }

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

Upvotes: 4

Related Questions