user7107845
user7107845

Reputation:

Setting delegate and datasource in custom UITableView

I'm trying to create a UITableView as a custom subview of my UIViewController, however the data is not showing up in the table. I suspect that the problem is my delegate and datasource for the table are not set. How can I link them? The UITableViewDataSource doesn't seem to work within a UITableView class?

UIViewController

    let projectDeck = ProjectDeck()
    projectDeck.frame = CGRect(x: 0, y: statusBarHeight + 132, width: screenWidth, height: screenHeight - 132)
    self.view.addSubview(projectDeck)

UITableView

class ProjectDeck: UITableView {

    var items = ["Test", "TestTest", "TestBestWestVest"]

    override func numberOfRows(inSection section: Int) -> Int {
        return items.count
    }

    override func cellForRow(at indexPath: IndexPath) -> UITableViewCell? {
        let cell = UITableViewCell()
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }

}

Upvotes: 0

Views: 1694

Answers (2)

Parth Adroja
Parth Adroja

Reputation: 13514

You need to add datasource and delegate reference.

You can do it by taking outlet or from the storyboard.

Using Outlets:

yourTableView.datasource = self
yourTableView. delegate = self

Using StoryBoard

ctrl-drag table view to viewcontroller next to first responder and click datasource and delegate.

Upvotes: 1

Punit
Punit

Reputation: 1340

set delegate and datasource in your viewcontrloller

i.e. in viewcontroller

projectdesc.tableview.datasource = self
projectdesc.tableview.delegate = self

and implements methods of tableview like cellforRow in viewccontroller

and be sure you are adding tableview as a subview in viewcontroller properly

Upvotes: 0

Related Questions