点击cell勾选

2018-06-14  本文已影响0人  做个有趣的程序员

前一段时间重写项目,碰到列表页需要点击cell变为勾选状态,最初的实现思路:
在didSelectRowAt indexPath方法中获取最后一次选中的cell的indexPath进行比较
试了一下效果,正常点击选中都没问题,每当滑动的时候再次点击cell,很惊喜的崩溃了,如图所示:


1111.png

分析原因,获取上一次选中的cell时,创建cell的时候强制解包可选值为nil的时候崩溃了,每当tableView滑动之后,在didSelectRowAtIndexPath方法里调用tableVIew.cellforRow方法创建cell,实际上cell没有值,强制解包导致崩溃,原因为每当tableView滑动之后,上一次选中的cell滑出屏幕以外区域,didSelectRowAtIndexPath方法只能获取当前显示区域内的cell。找到原因之后,切换另一种思路。
在didSelectRowAtIndexPath方法中获取当前选中cell的index值,并刷新

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == houseListTableView {
           //用于记录的选中的cell
            self.lastIndex = indexPath.row
        //选中之后刷新数据调用cellforrow方法
        self.houseListTableView.reloadData()
    }

在cellForRow方法里改变选中状态

if self.lastIndex == indexPath.row {
                cell.selectelImageView.image = UIImage(named: "xuanze_on")
                //选中的同时将家庭名称传给按钮的title
                if self.changeHouseNameClosure != nil {
                    self.changeHouseNameClosure!(cell.houseNameLabel.text!)
                }
            }else {
                cell.selectelImageView.image = UIImage(named: "xuanze_off")
            }
}

最终效果如下:


2222.gif

完美的解决了cell选中的问题,选择合适的解决思路事半功倍,节省很多时间。

上一篇下一篇

猜你喜欢

热点阅读