Open vikrantTech opened 3 years ago
Here is the implementation of delegate method and the callback of the delegate :-
class EmployeeTableViewDelegate
private var items : [T]!
var delegateCell : (T) -> () = {_ in }
init(items: [T]!, delegateCell: @escaping (T) -> Void) {
self.items = items
self.delegateCell = delegateCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Calling DidSelect")
let item = self.items[indexPath.row]
self.delegateCell(item)
}
}
make variable on the viewcontroller Same like Datasource :-
private var dataSource : EmployeeTableViewDataSource<EmployeeTableViewCell,EmployeeData>!
private var delegate: EmployeeTableViewDelegate
Use it same Like datasource and write down this code of bellow datasource code in func updateDataSource()
self.dataSource = EmployeeTableViewDataSource(cellIdentifier: "EmployeeTableViewCell", items: self.viewModel.empData.data, configureCell: { (cell, evm) in
cell.employee = evm
cell.employeeIdLabel.text = "\(evm.id)"
cell.employeeNameLabel.text = evm.employeeName
})
self.delegate = EmployeeTableViewDelegate(items: self.viewModel.empData.data, delegateCell: { empData in
print("DidSelect Data is:-", empData)
})
Setup tableview delegate same like datasource :-
DispatchQueue.main.async {
self.employeeTableView.rowHeight = 70
self.employeeTableView.delegate = self.delegate
self.employeeTableView.dataSource = self.dataSource
self.employeeTableView.reloadData()
}
That's it, Happy coding :)
How to use TableView Delegate in your project