Sobes.tech
Junior — Middle

Kā jūs īstenojat deleģētu, lai pārvaldītu tabulu jūsu projektā?

sobes.tech AI

Atbilde no AI

Lai pārvaldītu tabulu (UITableView) iOS, parasti tiek izveidota klase, kas realizē protokolus UITableViewDelegate un UITableViewDataSource. Delegāts ir atbildīgs par notikumu apstrādi, kas saistīti ar mijiedarbību ar tabulu, bet datu avots (data source) nodrošina datus.

Delegāta un datu avota realizācijas piemērs:

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let data = ["Ābols", "Banāns", "Apelsīns"]

    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("Izvēlētais elements: \(data[indexPath.row])")
    }
}

Projektā parasti tiek izveidota atsevišķa klase vai paplašinājums delegātam, lai atdalītu attēlošanas un notikumu apstrādes loģiku no kontroliera.