I have a UIViewController
in which I've embedded a UITableView
. If added an outlet to my ViewController class.
Because I don't want the ViewController
to get too heavy, I would like to put the methods of the UITableViewDataSource
protocol and UITableViewDelegate
protocol into separate classes.
So I created a TableViewDataSource.swift and a TableViewDelegate class:
class TableViewDelegate : NSObject, UITableViewDelegate {
//custom code here if required
}
class TableViewDataSource : NSObject, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "MyCellIdentifier"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = "left text"
cell.detailTextLabel?.text = "right text"
return cell
}
}
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = TableViewDataSource()
tableView.delegate = TableViewDelegate()
tableView.setNeedsDisplay()
// Do any additional setup after loading the view, typically from a nib.
}
}
In my Storyboard, I've created a prototype cell within the tableView with the identifier "MyCellIdentifier". I use this identifier to create a cell in my TableViewDataSource method.
However, if I run the app, I only see an empty tableView. The methods don't even get called even though I have set them in the viewDidLoad method of the ViewController. I also tried to enforce the tableView to redraw by calling setNeedsDisplay. This had no effect, too.