Junior — Middle
Jak implementujesz źródło danych dla tabeli w TableView?
sobes.tech AI
Odpowiedź od AI
Źródło danych dla UITableView jest implementowane za pomocą protokołów UITableViewDataSource i UITableViewDelegate. Głównym zadaniem jest dostarczenie tabeli liczby sekcji, liczby wierszy w każdej sekcji oraz komórek do wyświetlenia.
Przykład implementacji:
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let data = ["Jabłko", "Banan", "Wiśnia"]
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
}
}
W tym przykładzie tablica data pełni funkcję źródła danych. Tabela pyta dataSource o liczbę wierszy i zawartość komórek, które następnie są wyświetlane użytkownikowi.