iOS TableViewCell Checkmark的使用

在使用Tableview时当需要实现选中多个cell并标记的功能的时候我们可以用TableViewCell的Accessory属性。

Accessory属性有五个Type,分别是None、Disclosure Indicator、Detail Dislosure、Checkmark、Detail,而我们需要用Checkmark来标记选中状态。

只需要在didSelectRowAtIndexPath中写下如下代码即可


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)  {

          let cell = tableView.cellForRowAtIndexPath(indexPath)

          if cell!.accessoryType == UITableViewCellAccessoryType.Checkmark {
                cell!.accessoryType = UITableViewCellAccessoryType.None
          } else {
                cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
          }

}

这时候把tableview往下滚动你会发现不止一个cell被Checkmark,这是因为tableview的重用机制,假设系统创建了10个cell,而你的需展示的数据量有50个,你点击了第0个cell,这时候屏幕上显示的第0、11、22、33、44都被Checkmark了,因为他们用的是同一块内存空间,即

tableView.cellForRowAtIndexPath(0)
tableView.cellForRowAtIndexPath(22)
tableView.cellForRowAtIndexPath(33)
tableView.cellForRowAtIndexPath(44)

都是相等的cell。


正确的方法应该是用一个数组保存点击过的cell的下标,并reloadData在cell初始化的时候标记他们

var selectAry:NSMutableArray = []

didSelectRowAtIndexPath中

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
//        let cell = tableView.cellForRowAtIndexPath(indexPath)
//        
//        if cell!.accessoryType == UITableViewCellAccessoryType.Checkmark {
//            cell!.accessoryType = UITableViewCellAccessoryType.None
//        } else {
//            cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
//        }
        print(selectAry)
        
        if selectAry.count != 0 {
            if selectAry.containsObject(indexPath.row) {
                    
                selectAry.removeObjectAtIndex(selectAry.indexOfObject(indexPath.row))
                    
            } else {
                
                selectAry.addObject(indexPath.row)
                
            }
        } else {
            selectAry.addObject(indexPath.row)
        }
        
        tableView.reloadData()
        
    }

cellForRowAtIndexPath中

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath)
        
        if selectAry.count != 0 {
            if selectAry.containsObject(indexPath.row) {
                cell.accessoryType = UITableViewCellAccessoryType.Checkmark
            } else {
                cell.accessoryType = UITableViewCellAccessoryType.None
            }
        } else {
            cell.accessoryType = UITableViewCellAccessoryType.None
        }
        
        return cell
        
    }

你可能感兴趣的:(iOS TableViewCell Checkmark的使用)