Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: TableView in ViewController

I have a ViewController in the MainstoryBoard. I added the TableView to it.

MainStoryBoard:

enter image description here

In addition I have an array outside of the ViewController class and I want the objects inside the array to be shown in the TableView.

I can't figure out how to do it. I connected the delegate between the TableView and the ViewController.

like image 485
Eliko Avatar asked Jul 28 '15 10:07

Eliko


People also ask

What is Tableview in Swift?

Overview. Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app's content. For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings ...

Can we use Tableview in SwiftUI?

SwiftUI's List view is similar to UITableView in that it can show static or dynamic table view cells based on your needs.


2 Answers

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).

like image 116
Dharmesh Dhorajiya Avatar answered Sep 25 '22 15:09

Dharmesh Dhorajiya


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.

like image 24
Fullpower Avatar answered Sep 21 '22 15:09

Fullpower