Sobes.tech
Junior — Middle

Jak implementujesz delegata do zarządzania tabelą w swoim projekcie?

sobes.tech AI

Odpowiedź od AI

Aby zarządzać tabelą (UITableView) w iOS, zwykle tworzy się klasę, która implementuje protokoły UITableViewDelegate i UITableViewDataSource. Delegat odpowiada za obsługę zdarzeń interakcji z tabelą, a źródło danych (data source) za dostarczanie danych.

Przykład implementacji delegata i źródła danych:

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let data = ["Jabłko", "Banan", "Pomarańcza"]

    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("Wybrany element: \(data[indexPath.row])")
    }
}

W projekcie zwykle tworzy się osobną klasę lub rozszerzenie dla delegata, aby oddzielić logikę wyświetlania i obsługi zdarzeń od kontrolera.