UITableView Checkmarks disappear when scrolling

前端 未结 5 1708
一整个雨季
一整个雨季 2020-11-30 08:38

I have to make checkmarks on a tableView, but if I\'m scrolling and one check marked cell is not visible and I scroll back the checkmark disappeared.

While running

5条回答
  •  爱一瞬间的悲伤
    2020-11-30 08:52

    Create an Array of tuples to store row and section values:

    var selectedCells:[(row: Int, section: Int)] = []
    

    In your cellForRowAtIndexPath, check if you have any selectedCellValues. If so, add an accessoryType for that cell and break out of the loop,

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    
        let cell = tableView.dequeueReusableCellWithIdentifier("SettingsCell", forIndexPath: indexPath) as SettingsCustomCell
    
        var rowNums:NSNumber = indexPath.row
        var sectionNums:NSNumber = indexPath.section
    
        var selectedRow:Int
        var selectedSection:Int
    
        if(selectedCells.count > 0){
            for tuple in selectedCells{
    
                selectedRow = tuple.row
                selectedSection = tuple.section
    
                if(selectedRow == rowNums && selectedSection == sectionNums){
                    cell.accessoryType = UITableViewCellAccessoryType.Checkmark
                    break
                }else{
                    cell.accessoryType = UITableViewCellAccessoryType.None
                }
            }
        }else{
            cell.accessoryType = UITableViewCellAccessoryType.None
        }
    
        var keyValue = listOfSectionTitles[indexPath.section]
        var items: [NSString] = dictionaryOfCellTitles.objectForKey(keyValue) as [NSString]
    
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }
    

    Handle selectedcellvalues in didSelecteRowAtIndexPath:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
        let cell = tableView.cellForRowAtIndexPath(indexPath)
    
        if(cell?.accessoryType == UITableViewCellAccessoryType.None){
            cell?.accessoryType = UITableViewCellAccessoryType.Checkmark
            selectedCells.append(row:indexPath.row, section:indexPath.section)
        }else{
            var rowToDelete = indexPath.row
            var sectionToDelete = indexPath.section
    
            for var i=0; i < selectedCells.count; i++
            {
                if(rowToDelete == selectedCells[i].row && sectionToDelete == selectedCells[i].section){
                    selectedCells.removeAtIndex(i)
                    cell?.accessoryType = UITableViewCellAccessoryType.None
                }
            }
        }
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    

提交回复
热议问题