labnxx labnxx - 2 months ago 14
iOS Question

self.tableView.delegate = self Swift iOS9

If I have a UIViewController and I hook up a tableView to it in storyboards, connect the tableview outlet, and then connect the datasource and delegate methods via the connections inspector (cntrl+drag to vc orange circle icon), do I still need to add self.tableView.delegate = self to the actual view controller? Of course in the actual vc I'm implementing the tableView data/delegate protocols.

Also I'm assuming whatever the answer is the same would go for a collection view controller being connected via storyboard the same way?

What are the pros and cons of adding it?

class FooController:UIViewController, UITableViewDataSource, UITableViewDelegate{


@IBOutlet weak var tableView: UITableView!


override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
{


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
{
}

Answer

do I still need to add self.tableView.delegate = self to the actual view controller?

No. You are doing this by making the connection in the storyboard. They are exactly the same thing: an assignment to the delegate property, expressed in two different ways (one in code, one "graphically" in Interface Builder). You only need to do one of them.

But if your view controller were a table view controller (UITableViewController subclass), then you would do neither, because the table view controller is already the table view's data source and delegate. The same is true for a collection view controller (UICollectionViewController subclass); it is already the collection view's data source and delegate.

Comments