使用全选选项进行swift 3.0多重选择

时间:2017-09-25 06:01:13

标签: ios uitableview swift3

我在表格视图中添加了数据,我手动添加了"选择全部"当用户选择第一个选项时,选择列表在第一个位置,选择全部,然后选择所有项目到列表中,并选择相同时取消选择。我已经尝试了下面的代码,但它没有工作,所以任何人都可以帮我解决这个问题

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
    for i in 0 ..< self.getStudentName.count {
        cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
        print (i) //i will increment up one with each iteration of the for loop

    }

}
var unchecked = true
 @IBAction func btnCheckBoxClick(_ sender: Any) {

if unchecked == true {
           //(sender as AnyObject).setImage(UIImage(named: "selectedItem"), for: .normal)
            cell?.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
            //unchecked = false
            let cello = ObjTableview.cellForRow(at: indexPath!)
            print(cello!)
            ObjTableview.reloadData()
        }else
        {
            //(sender as AnyObject).setImage(UIImage(named: "unSelectedItem"), for: .normal)
            cell?.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
           // unchecked = true
        }
}

1 个答案:

答案 0 :(得分:1)

Jayprakash,你快到了。你需要修改一些行 -

以下是修改后的代码段

var unchecked:Bool = true

@IBAction func btnCheckBoxClick(_ sender: Any) {

    if(unchecked){

        unchecked = false
    }
    else{

        unchecked = true
    }


    ObjTableview.reloadData()


}



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if(indexPath.row == 0){

            btnCheckBoxClick(sender: UIButton())

      }

 }


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

        let cell : SelectUserCell!
        cell = tableView .dequeueReusableCell(withIdentifier: "SelectUserCell", for: indexPath) as! SelectUserCell
        cell.selectionStyle = UITableViewCellSelectionStyle.none


       if(unchecked){

              cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)

         }
       else{

              cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
         }


   // Do your stuff here

   return cell
}

跳转它将简化您的代码结构。