美文网首页
iOS tableView自定义多选

iOS tableView自定义多选

作者: 做个有趣的程序员 | 来源:发表于2018-07-11 15:49 被阅读0次

    tableView列表中会有单选和多选功能,cell多是自定义,网上的一些文章逻辑都比较复杂,主要问题还是要梳理清楚。实现方式:

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell:FamilyRoomTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "room", for: indexPath) as? FamilyRoomTableViewCell
                cell.selectionStyle = .none
                cell.selectedBtn.tag = indexPath.row + 1000
                //模型赋值
                cell.setmodel(model: self.roomListArray![indexPath.row])
                cell?.changeModelBlock = { (tag) ->Void in
                    cell.roomModel = self.roomListArray![tag-1000]
                    if cell.roomModel?.isRoomSelected == "0" {
                        cell.roomModel?.isRoomSelected = "1"
                        self.roomNameArray.append((cell.roomModel?.groupName)!)
                    }else {
                        cell.roomModel?.isRoomSelected = "0"
                        //array没有移除object元素的方法,所以采用filter函数进行过滤
                        //使用nsmutableArray方法移除当前的object,如果是可选类型,打印出来的值带有option字样,如果不是可选类型,打印出来的值为unicode码(暂时不知道原因)
                         self.roomNameArray = self.roomNameArray.filter({$0 != cell.roomModel?.groupName})
                    }
                    //重新赋值这一步很关键
                    self.roomListArray![tag-1000] = cell.roomModel!
                    self.familyTableView.reloadData()
                    print("**********当前的房间数组*********\(String(describing: self.roomNameArray))")
                }
                return cell
        }
    

    思路:根据btn的tag与cell的indexPath关联,模型里手动添加isRoomSelected字段判断是否选中,如果是放在该方法根据isRoomSelected去改变btn的背景图片的选择状态,由于cell的重用机制,在滑动的时候会导致btn的图片勾选状态错乱。
    解决问题关键:将选中状态与model进行绑定,解决重用问题
    cell中的代码

        func setmodel(model:HouseDeviceGroupModel?) {
            roomModel = model
            roomNameLabel.text = model?.groupName
            selectedBtn.isSelected = (model?.isRoomSelected == "1")
    //        // 按钮默认选中
            if selectedBtn.isSelected {
                //选中
                selectedBtn.setImage(UIImage(named: "xuanze_on"), for: .normal)
            }else {
                //不选中
                selectedBtn.setImage(UIImage(named: "xuanze_off"), for: .normal)
            }
        }
    

    最终效果如下:


    2222.gif

    完美解决重用问题

    相关文章

      网友评论

          本文标题:iOS tableView自定义多选

          本文链接:https://www.haomeiwen.com/subject/qxvhpftx.html