Junior — Middle
Can you explain what the UITableViewDataSource protocol is in iOS and how it is used to display data in a table?
sobes.tech AI
Answer from AI
UITableViewDataSource is a protocol in iOS that defines methods for providing data and managing the content of a table (UITableView). It is responsible for what data is displayed and in what form within the table cells.
Main protocol methods:
tableView(_:numberOfRowsInSection:)— returns the number of rows in a section.tableView(_:cellForRowAt:)— returns a cell (UITableViewCell) for a specific row, where data display is configured.
Usage:
- A class (e.g., UIViewController) declares that it implements
UITableViewDataSource. - Implements the required protocol methods.
- Sets itself as the data source for the table:
tableView.dataSource = self.
Example:
class MyViewController: UIViewController, UITableViewDataSource {
let data = ["Apple", "Banana", "Cherry"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
return cell
}
}
Thus, UITableViewDataSource links data with the visual representation in the table.