Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

ios - UITableViewCell Checkmark Being Added to multiple rows when one is tapped

I have a tableview where not all of the cells are visible at once. I am trying to make it so that when a row is tapped it adds a checkmark accessory to the cell. My issue is that it adds it to other rows as well. In my table view there are 4 rows fully showing and a fifth one barely showing. If I check the first box it will then add a check mark to every fifth box (e.g. indexPath.row = 0,5,10,15...) despite the indexPath.row being different.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

     let cell: DropDownMenuCell = tableView.dequeueReusableCellWithIdentifier("DropDownMenuCell", forIndexPath: indexPath) as! DropDownMenuCell
     cell.dropDownCellLabel?.text = DropDownItems[indexPath.row].Name
     return cell

}


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

    let selectedCell: DropDownMenuCell = tableView.cellForRowAtIndexPath(indexPath) as! DropDownMenuCell
    print(indexPath.row)
    if selectedCell.accessoryType == .None {
        selectedCell.accessoryType = .Checkmark
    } else {
        selectedCell.accessoryType = .None
    }

}

Edit: Apologies for the duplicate, my initial search for this question didn't show the other question. I got a working answer here in swift already or I would try and go through the objective c post to solve my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Maintain in your Data source which cell is to be selected.

Then in cellForRowAtIndexPath:

if (DropDownItems[indexPath.row].isSelected) {
    cell.accessoryType = .Checkmark
} else {
    cell.accessoryType = .None
}

and in your didSelectRowAtIndexPath Method:

if(DropDownItems[indexPath.row].isSelected) {
    DropDownItems[indexPath.row].isSelected = false
} else {
    DropDownItems[indexPath.row].isSelected = true
}

self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...