Junior — Middle
How do you implement a data source for a table in TableView?
sobes.tech AI
Answer from AI
The data source for UITableView is implemented through the UITableViewDataSource and UITableViewDelegate protocols. The main task is to provide the table with the number of sections, the number of rows in each section, and the cells to display.
Example implementation:
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
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
}
}
In this example, the data array acts as the data source. The table requests the number of rows and the content of the cells from the dataSource, which are then displayed to the user.