Search code examples
swiftuitableviewcellsdidselectrowatindexpathsections

Swift: UITableView cells being affected by cells in another section


I have a function that changes the accessoryType of cells in Section 0 to a checkmark. It works great and displays a checkmark when selected, but if a cell in Section 1 or Section 2 is selected, it'll move the checkmarks on Section 0. If someone could tell me how to fix this, that'd be great.

    //Adds Checkmark to Cells when Selected
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let section = 0
        let numberOfRows = tableView.numberOfRowsInSection(section)
        for row in 0..<numberOfRows {
            if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
                cell.accessoryType = row == indexPath.row ? .Checkmark : .None
            }
        }
    }

Solution

  • Since your cell are reuse, if you don't set back settings of your cell when you create them, this will happen.

    You need to set accessoryType of your cell back in cellForRowAtIndexPath function override.