选中和取消选中表视图控制器中的按钮

时间:2018-07-26 07:50:34

标签: ios swift uitableview swift4

我是ios swift4的新手,我只是在表视图控制器中创建检查和取消选中按钮,我的任务是使用检查按钮选择表中的项目,我想取消选中通过单击取消选中按钮选中的项目。我来解决这个问题

1 个答案:

答案 0 :(得分:0)

daysRemainderTableView中,使用名称为daysSelectionimageView的imageview。这是在tableviewcell中选择和取消选择行的示例。

     @IBOutlet weak var daysRemainderTableView: UITableView!

         var days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]

var selectedDaysArray = [Int]() 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return days.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "RemainderDaysCell", for: indexPath)as! RemainderDaysCell
                cell.remainderDaysLabel.text = "\(days[indexPath.row])"


                if selectedDaysArray.contains(indexPath.row){
                    cell.daysSelectionimageView.image = #imageLiteral(resourceName: "selectedImage")
                }else{
                    cell.daysSelectionimageView.image = #imageLiteral(resourceName: "ring")
                }
                return cell
            }

            func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                if let cell = tableView.cellForRow(at: indexPath) as? RemainderDaysCell
                {
                    if selectedDaysArray.isEmpty{
                        self.selectedDaysArray = [Int]()
                    }
                    if selectedDaysArray.contains(indexPath.row){
                        if let indexElement = selectedDaysArray.index(of: indexPath.row){
                            cell.daysSelectionimageView.image = #imageLiteral(resourceName: "ring")
                            selectedDaysArray.remove(at: indexElement)
                        }
                    }else{
                        cell.daysSelectionimageView.image = #imageLiteral(resourceName: "selectedImage")
                        selectedDaysArray.append(indexPath.row)
                    }
                }
            }

我正在检查indexpath和didSelectRow ai indexpath的cellforrow中的selectedDaysArray,如果selectedDaysArray已经选择了索引,那么我正在删除元素,如果不是,则将indexemement附加到selectedDaysArray上。