UITableView Data Source and Delegate (iOS – Xcode)The Data Source is responsible for providing data to the table view. It tells the table view:
The Delegate handles user interactions and appearance behavior of the table view. It controls:
👉 Simple idea:
To use a table view, your ViewController must conform to:
UITableViewDataSource
UITableViewDelegate
Represents the position of a cell
Contains:
UITableView
↓
DataSource → provides data
Delegate → handles interaction
↓
UITableViewCell (rows)
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
let fruits = ["Apple", "Banana", "Mango", "Orange"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
👉 Tells how many rows to display
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = fruits[indexPath.row]
return cell
}
👉 Creates and configures each cell
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected: \(fruits[indexPath.row])")
}
👉 Called when user taps a row
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
👉 Controls row size
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
Draw:
UITableView
↓
DataSource → rows + content
Delegate → tap + behavior
↓
Cells (UITableViewCell)
let fruits = ["Apple", "Banana", "Mango"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = fruits[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected \(fruits[indexPath.row])")
}
tableView.reloadData()
cellForRowAt method.didSelectRowAt method.reloadData() used?Data Source → provides data (rows + content)
Delegate → handles user interaction
Key methods:
numberOfRowsInSectioncellForRowAtdidSelectRowAtUses IndexPath to access data
reloadData() updates table view
Essential for all list-based apps
Open this section to load past papers