UITableViewDataSource
The methods that an object adopts to manage data and provide cells for a table view.
Declaration
@MainActor protocol UITableViewDataSource : NSObjectProtocolMentioned in
Overview
Table views manage only the presentation of their data; they don’t manage the data itself. To manage the data, you provide the table with a data source object — an object that implements the UITableViewDataSource protocol. A data source object responds to data-related requests from the table. It also manages the table’s data directly, or coordinates with other parts of your app to manage that data. Other responsibilities of the data source object include:
Reporting the number of sections and rows in the table.
Providing cells for each row of the table.
Providing titles for section headers and footers.
Configuring the table’s index, if any.
Responding to user- or table-initiated updates that require changes to the underlying data.
Only two methods of this protocol are required, and they’re shown in the following example code.
// Return the number of rows for the table.
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
// Provide a cell object for each row.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Fetch a cell of the appropriate type.
let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)
// Configure the cell’s contents.
cell.textLabel!.text = "Cell text"
return cell
}Use other methods of this protocol to enable specific features for your table. For example, you must implement the tableView(_:commit:forRowAt:) method to enable the swipe-to-delete feature for rows.
For information about how to create and configure your table’s cells using your data source object, see Filling a table with data.
Specify the location of rows and sections
Table views communicate the location of cells to you using the row and section properties of NSIndexPath objects. Row and section indexes are zero based, so the first section is at index 0, the second at index 1, and so on. Similarly, the first row of each section is at index 0, which means you need both the section and row values to identify a row uniquely. If your table has no sections, you need only the row value.
[Image]
Topics
Providing the number of rows and sections
Providing cells, headers, and footers
tableView(_:cellForRowAt:)tableView(_:titleForHeaderInSection:)tableView(_:titleForFooterInSection:)