簡體   English   中英

Swift 根據 UITableview 單元格 select 在數組中添加和刪除項目並取消選擇

[英]Swift Add and Remove Item into array based on UITableview cell select and deselect

就我而言,我在codable的幫助下將JSON數據加載到Tableview中。 該表查看多個selectdeselect選中復選標記選項可用。 現在,如果用戶取消選擇單元格需要從同一個數組中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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM