UITableViewCell复选标记被点击时添加到多行

我有一个tableview,并不是所有的单元格都是可见的。 我试图做到这一点,当一个行被点击时,它添加一个复选标记附件的单元格。 我的问题是,它也将其添加到其他行。 在我的桌子上,有四排完全显示,第五个几乎没有显示。 如果我检查第一个框,然后将添加一个复选标记到每五个框(例如indexPath.row = 0,5,10,15 …)尽pipeindexPath.row是不同的。

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 } } 

编辑:道歉的重复,我最初search这个问题没有显示其他问题。 我已经在这里迅速得到了一个工作的答案,否则我会尝试通过目标c后解决我的问题。

在数据源中维护要select的单元格。

然后在cellForRowAtIndexPath中:

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

并在你didSelectRowAtIndexPath方法:

 if(DropDownItems[indexPath.row].isSelected) { DropDownItems[indexPath.row].isSelected = false } else { DropDownItems[indexPath.row].isSelected = true } self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) 

在Swift 3中,这应该有所帮助:

 import UIKit class ViewController: UITableViewController { let foods = ["apple", "orange", "banana", "spinach", "grape"] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return foods.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = foods[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark { tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none } else { tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }