Sobes.tech
Junior — Middle

How do you implement a delegate to manage a table in your project?

sobes.tech AI

Answer from AI

To manage a table (UITableView) in iOS, a class implementing the UITableViewDelegate and UITableViewDataSource protocols is usually created. The delegate handles interaction events, while the data source provides data.

Example implementation:

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let data = ["Apple", "Banana", "Orange"]

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

Typically, a separate class or extension is created for the delegate and data source to separate display logic and event handling from the controller.

How do you implement a delegate to manage a table in… - sobes.tech