Junior — Middle
Kako implementirate delegata za upravljanje tabele u vašem projektu?
sobes.tech АИ
Одговор од АИ
Za upravljanje tabelom (UITableView) u iOS obično se kreira klasa koja implementira protokole UITableViewDelegate i UITableViewDataSource. Delegat je odgovoran za obradu događaja interakcije sa tabelom, dok izvor podataka (data source) obezbeđuje podatke.
Primer implementacije delegata i izvora podataka:
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let data = ["Jabuka", "Banana", "Narandža"]
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
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Izabrani element: \(data[indexPath.row])")
}
}
U projektu se obično kreira posebna klasa ili proširenje za delegata, kako bi se odvojila logika prikaza i obrade događaja od kontrolera.