martin
martin

Reputation: 1974

Swift - Override functions in UIViewController vs UITableViewController

When I use the UITableViewController to create a tableView, you get a lot of override functions, but when you use a regular UIViewController you get an error when using these same override functions and you are forced to change them to regular functions. I believe this is why my core data won't load into my cells, and tried to use the viewDidLoad function to get my data to load.

I know my code should work since all I'm trying to do is transfer all my code from a UITableViewController to a UIViewController, and my code worked in my UITableViewController.

My effort so far:

override func viewDidLoad() {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Configure the cell...

        let CellID:NSString = "CELL"

        var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell

        if let ip = indexPath as Optional {

            var data:NSManagedObject = myList[ip.row] as NSManagedObject
            cell.textLabel!.text = data.valueForKeyPath("username") as? String
        }

        return cell
    }
}

Are the override functions the reason my cells are empty, or are there other aspects when using a regular UIViewController to show a tableView?

Any suggestions would be appreciated.

Upvotes: 0

Views: 1519

Answers (1)

Lyndsey Scott
Lyndsey Scott

Reputation: 37300

(1) You have to add UITableViewDelegate to the class in order to access the delegate methods, ex:

class ViewController: UIViewController, UITableViewDelegate {

After adding the UITableViewDelegate to the class, your UITableView delegate functions should auto-complete.

Also, make sure to set the UITableView's delegate to self in order to have the delegate methods populate the table.

(2) Right now, your cellForRowAtIndexPath method is within your viewDidLoad. Move it so it's not contained within any other method.

Upvotes: 1

Related Questions