Jay Ess Jay Ess - 1 month ago 9
Swift Question

Using UITableView without a storyboard

I'm trying to set a tableView as a subview in my viewController. But without using the storyboard! I'm trying this code, but it doesn't seem to work and I can't understand why..
So this is the code in which the tableview should be created:

func TableView(position: CGRect, allRecipes: [Recipe]) -> UITableView {
let tableView: UITableView = UITableViewForAllRecipes(style: UITableViewStyle.Plain).tableView


return tableView;
}


.

and this is my tableviewcontroller (UITableViewForAllRecipes)

class UITableViewForAllRecipes: UITableViewController {

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

cell.textLabel.text = "ok"

return cell
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
println("nosit")
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("tv")
return 3
}


}

Does anyone see what I'm doing wrong? As it doesn't even seem to print those "nosit" and "tv", so It doesn't reach that code.. I didn't get anything out of debugging also..

Answer

@Swipesight is right. The reason why you see an empty tableview:

  • You create an instance of UITableViewForAllRecipes, the tableview controller holds a tableview and itself as that tableview's datasource and delegate.
  • Then you grab the tableview, add it as a subview, but since tableview holds its delegate as weak reference, when you quit the TableView() func, the tableviewcontroller itself is released, since no more strong ref.
  • When the tableview being rendered, it asks its datasource, which is nil and you get an empty table view.

Possible fix:

Hold a strong ref to your tableviewcontroller in your parent view controller

e.g

func TableViewController(position: CGRect, allRecipes: [Recipe]) -> UITableViewForAllRecipes {
    return UITableViewForAllRecipes(style: UITableViewStyle.Plain)
}

add a property in your parent view controller

var tableViewController: UITableViewForAllRecipes?

Then in your function where you call TableView

self.tableViewController = self.TableViewController(xxxx)
self.view.addSubview(self.tableViewController!.tableView)