如果在表视图中选中复选框,如何保存选定的数组

时间:2018-07-28 09:12:34

标签: swift uitableview

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return arraylist.count
}
 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 50.0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = PopupCellTableViewCell()

    cell  = (tableView.dequeueReusableCell(withIdentifier: "advnccell", for: indexPath) as? PopupCellTableViewCell)!

    cell.bgView = Utilities().viewborder(vw: cell.bgView )

    let dict = arraylist[indexPath.row] as! NSDictionary

    let cd  = dict.value(forKey: "Code") as? String ?? ""
    let desc  = dict.value(forKey: "Description") as? String ?? ""

    cell.tittleLbl.text = cd + " - " + desc

    if selectedRows.contains(indexPath)
    {
        cell.checkBtn.setImage(UIImage(named:"check"), for: .normal)
    }
    else
    {
        cell.checkBtn.setImage(UIImage(named:"uncheck"), for: .normal)
    }
    if (cell.checkBtn.currentImage?.isEqual(UIImage(named: "check")))!
    {
        UserDefaults.standard.set(cell.tittleLbl.text, forKey: "tittle")

    }

     cell.btnAction.tag = indexPath.row
    cell.btnAction.addTarget(self, action: #selector(checkBoxSelection(_:)), for: .touchUpInside)
    return cell
}



// checkbox selection
@objc func checkBoxSelection(_ sender:UIButton)
{
    let selectedIndexPath = IndexPath(row: sender.tag, section: 0)
    if self.selectedRows.contains(selectedIndexPath)
    {
        self.selectedRows.remove(at: self.selectedRows.index(of: selectedIndexPath)!)
    }
    else
    {
        self.selectedRows.append(selectedIndexPath)
    }
    self.tableVw.reloadData()
}

目前我只获得一个值,如果我选择了多个复选按钮,我将如何获得

1 个答案:

答案 0 :(得分:0)

修复代码的这一部分:

if selectedRows.contains(indexPath)
{
    cell.checkBtn.setImage(UIImage(named:"check"), for: .normal)
    UserDefaults.standard.set(cell.tittleLbl.text, forKey: "tittle")
}
else
{
    cell.checkBtn.setImage(UIImage(named:"uncheck"), for: .normal)
}