Junior — Middle
Ako implementujete zdroj dát pre tabuľku v TableView?
sobes.tech AI
Odpoveď od AI
Zdroj dát pre UITableView je implementovaný prostredníctvom protokolov UITableViewDataSource a UITableViewDelegate. Hlavnou úlohou je poskytnúť tabuľke počet sekcií, počet riadkov v každej sekcii a bunky na zobrazenie.
Príklad implementácie:
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let data = ["Jablko", "Banán", "Čerešň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
}
}
V tomto príklade pole data slúži ako zdroj dát. Tabuľka žiada od dataSource počet riadkov a obsah buniek, ktoré sú potom zobrazené používateľovi.