Working with TableViews

In Main.storyboard, drag a Table View into the view where you want the table.

Adding a Table View

Control drag from the Table View to the View Controller and set the DataSource and the Delegate.

tableview2

The next step is to add items to the View Controller Class.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate

Two common functions that need to be added are numberOfRowsInSection and cellForRowAt indexPath: IndexPath. In numberOfRowsInSection return the count of items in the array to display or some fixed, suitable number. In cellForRowAt indexPath: IndexPath the current (indexPath.row) value of the arrayVariable is set equal to the cell text. Other items can be added such as detailTextLabel.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
	let cell = UITableViewCell()	
	cell.textLabel?.text = arrayVariable[indexPath.row]
	return cell
 }

Another step is to reload the data in the table after a change has been made. This can done in viewDidAppear function.

override func viewWillAppear(_ animated: Bool)
{
	tableView.reloadData()
}

Another example using Table View can be seen in the Split View example.


Index


Comments, Corrections, Suggestions: David Bourne (david@boomer.org)
My iOS and tvOS Apps and iBooks