ms_abc ms_abc - 1 year ago 132
Swift Question

Setting data source and delegate crashes the app for UITableView

New here so bear with me... I have a simple View Controller which contains a

UITableView
. I am not sure whether I should connect the data source and the data controller to the View Controller. Doing so crashes the app, but if I don't do it, I don't see any output in the table view when I run the app. How should this work?

class ViewController: UIViewController {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else {
return 2
}
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "One"
} else {
return "Two"
}
}

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


let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell


let cellImage: UIImage = UIImage (named: "generic.png")!

print("cell")

if indexPath.section == 0 {
cell.textLabel!.text = "Section 0, Row 0"
cell.detailTextLabel!.text = "Detail goes here."
cell.imageView!.image = cellImage
print("inside cell1")
}
else{
if indexPath.row == 0 {
cell.textLabel!.text = "Section 1, Row 0"
cell.detailTextLabel!.text = "Detail goes here."
cell.imageView!.image = cellImage
print("inside cell2")
}
else {
cell.textLabel!.text = "Section 1, Row 1"
cell.detailTextLabel!.text = "Detail goes here."
cell.imageView!.image = cellImage
print ("inside cell3")
}
}
return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

}

Answer Source

Your view controller needs to conform to UITableViewDataSource and UITableViewDelegate in order to use those methods. Change your class declaration to this:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download