In my case, I am loading JSON
data into Tableview
with help of codable
. The tableview multiple select
and deselect
checkmark options available. Now, I need to Insert
selected values into one array
and same time if user deselect the cell need to remove
relevant value from same array. The stored array data, I am going to use in multiple viewcontroller
. How to achieve this?
JSON Codable
// MARK: - Welcome
struct Root: Codable {
let status: Bool
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let userid, firstname, designation: String?
let profileimage: String?
}
My Codebase for Tableview Delegate
var studentsData = [Datum]()
var sessionData = [Datum]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.studentsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
let item = self.studentsData[indexPath.row]
cell.nameCellLabel.text = item.firstname
cell.subtitleCellLabel.text = item.designation
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let item = self.studentsData[indexPath.row]
if let cell = tableView.cellForRow(at: indexPath) {
if cell.accessoryType == .checkmark {
cell.accessoryType = .none
// UnCheckmark cell JSON data Remove from array
if let index = sessionData.index(of:item) {
sessionData.remove(at: index)
}
print(sessionData)
} else {
cell.accessoryType = .checkmark
// Checkmark selected data Insert into array
self.sessionData.append(item)
print(sessionData)
}
}
}