Junior — Middle
Ako implementujete delegáta na správu tabuľky vo vašom projekte?
sobes.tech AI
Odpoveď od AI
Na správu tabuľky (UITableView) v iOS sa zvyčajne vytvára trieda, ktorá implementuje protokoly UITableViewDelegate a UITableViewDataSource. Delegát je zodpovedný za spracovanie udalostí interakcie s tabuľkou, zatiaľ čo zdroj dát (data source) za poskytovanie dát.
Príklad implementácie delegáta a zdroja dát:
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let data = ["Jablko", "Banán", "Pomaranč"]
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("Vybraný prvok: \(data[indexPath.row])")
}
}
V projekte sa zvyčajne vytvára samostatná trieda alebo rozšírenie pre delegáta, aby sa oddelila logika zobrazenia a spracovania udalostí od riadiča.