Swift: TableView in ViewController
i might be late and you may have fixed this by now. The error you are getting is due to your variable or constant returning a nil value. to test this you can assign a value to it (hard code it) and check the full code if it is working and then change it to your array, unfortunately i do stuff programmatically and not very familiar with the storyboard.
if you share your code we will be assist you if this is not yet sorted.
You add a new table view instance variable below the class declaration.
@IBOutlet weak var tableView: UITableView!
To conform to the UITableViewDelegate
and UITableViewDataSource
protocol just add them separated by commas after UIViewController
in the class declaration
After that we need to implement the tableView(_:numberOfRowsInSection:)
, tableView(_:cellForRowAtIndexPath:)
and tableView(_:didSelectRowAtIndexPath:)
methods in the ViewController
class and leave them empty for now
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 // your number of cells here
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// your cell coding
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// cell selected code here
}
}
As mentioned by @ErikP in the comments, you also need to set
self.tableView.delegate = self
self.tableView.dataSource = self
in the viewDidLoad
method.
(or in Storyboard works well too).