Sobes.tech
Junior — Middle

Kaip įgyvendinate delegatą, skirtą valdyti lentelę jūsų projekte?

sobes.tech AI

Atsakymas iš AI

iOS dažniausiai kuriama klasė, kuri įgyvendina protokolus UITableViewDelegate ir UITableViewDataSource, norint valdyti lentelę (UITableView). Delegatas atsakingas už sąveikos su lentele įvykių apdorojimą, o duomenų šaltinis (data source) – už duomenų teikimą.

Delegato ir duomenų šaltinio įgyvendinimo pavyzdys:

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let data = ["Obuolys", "Bananas", "Apelsinas"]

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

Projektą dažniausiai kuriama atskira klasė arba išplėtimas delegatui, siekiant atskirti rodymo ir įvykių apdorojimo logiką nuo valdiklio.