[英]Swift Add and Remove Item into array based on UITableview cell select and deselect
就我而言,我在codable
的幫助下將JSON
數據加載到Tableview
中。 該表查看多個select
和deselect
選中復選標記選項可用。 現在,如果用戶取消選擇單元格需要從同一個數組中remove
相關值,我需要Insert
選定的值插入到一個array
中。 存儲的數組數據,我將在多個viewcontroller
中使用。 如何做到這一點?
JSON 可編碼
// MARK: - Welcome
struct Root: Codable {
let status: Bool
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let userid, firstname, designation: String?
let profileimage: String?
}
我的 Tableview 代表代碼庫
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)
}
}
}
您可以通過搜索其索引來刪除數組中的項目
let index = try? array.firstIndex(where: { $0. userid == sessionData[indexPath.row].userid })
或者您可以使用此檢查自定義對象數組是否包含特定的自定義 object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.