Swift 3.0 multiple selection with select all cell

前端 未结 4 1993
心在旅途
心在旅途 2020-12-10 16:58

I have added data in table view and I have manually added \"select all\" option to the list at first position, now when the user selects the first option which is \'select a

4条回答
  •  旧时难觅i
    2020-12-10 17:32

    Hello u can take cheboxbutton action method inside view controller with addtarget method and assign tag indexpath.row so u can easily get the indexpath. from below code u can get the idea.

    class ViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var ObjTableview: UITableView!
    var arrStudent = ["1","2","3","4","5"]
    var arrSelectedStudent :[Int] = []
    var selectAll:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //MARK: UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrStudent.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // create a new cell if needed or reuse an old one
        let cell = ObjTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SelectUserCell
        // set the text from the data model
        cell.selectionStyle = UITableViewCellSelectionStyle.none
       // cell.lblStudentName.text = getStudentName[indexPath.row]
        cell.lblStudentName.text = arrStudent[indexPath.row]
        cell.btnCheckbox.tag = indexPath.row
       cell.btnCheckbox.addTarget(self, action:#selector(btnCheckBoxClick(sender:)), for: .touchUpInside)
    
    
        if selectAll {
            cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
        }else{
        if arrSelectedStudent.contains(indexPath.row){
            cell.btnCheckbox.setImage(UIImage(named: "selectedItem"), for: .normal)
        }else{
            cell.btnCheckbox.setImage(UIImage(named: "unSelectedItem"), for: .normal)
        }
        }
    
             return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     }
    
    func btnCheckBoxClick(sender: UIButton) {
        if sender.tag == 0{
            selectAll = true
        }else
        {
            selectAll = false
        if let index = arrSelectedStudent.index(of: sender.tag) {
            arrSelectedStudent.remove(at: index)
        }else{
            arrSelectedStudent.append(sender.tag)
        }
        }
    
        ObjTableview.reloadData()
    }}
    

提交回复
热议问题