TableView选中的单元格 – 当标题滚动不见时检查标记消失,并检查新单元格

我有一个tableViewCell,在cellType的accessoryType中使用复选标记。 我有一个函数,将单元格的内容放入textField中,同样在文本字段未被选中时将其从文本字段中移除。

它似乎工作正常,但如果我检查一个单元格,并希望检查一个单元格不可见(IOW)我需要滚动tableView,被检查的单元格(现在不可见)似乎取消自己(只有当我检查一个新的可见细胞)。

多重select仅适用于可见细胞。

这是我的代码:

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) let row = indexPath.row cell.textLabel?.text = painArea[row] cell.accessoryType = .None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //selectedRow = indexPath tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = indexPath.row let cell = tableView.cellForRowAtIndexPath(indexPath) if cell!.accessoryType == .Checkmark { cell!.accessoryType = .None } else { cell!.accessoryType = .Checkmark } populateDescription() print(painArea[row]) } var painDescription = ["very sore"] func populateDescription() { painDescription.removeAll() severityText.text = "" for cell in tableView.visibleCells { if cell.accessoryType == .Checkmark { painDescription.append((cell.textLabel?.text)! + " ") } var painArea = "" var i = 1 while i <= painDescription.count { painArea += painDescription[i-1] + "~" i = i + 1 } severityText.text = painArea } 

我希望我正在充分解释自己。 我不希望不可见的单元格被取消选中,从而从我的文本字段中删除,除非我不选中它。

任何想法将不胜感激。

亲切的问候

韦恩

由于Cell的可重用性而引起的攻击。 不要在didSelect中设置复选Checkmark ,而是尝试在cellForRowAtIndexPath设置。 你也需要像这样创buildmodel类来解决你的问题

 class ModelClass: NSObject { var isSelected: Bool = false //Declare other property that you are using cellForRowAtIndexPath } 

现在检查这个isSelectedcellForRowAtIndexPath像下面。

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) let row = indexPath.row let modelClass = painArea[row] cell.textLabel?.text = modelClass.name if modelClass.isSelected { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } 

现在改变你的didSelect像这样

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var modelClass = painArea[indexPath.row] modelClass.isSelected = !modelClass.isSelected self.tableView.reloadData() populateDescription() print(painArea[row]) } 

希望这会帮助你。

这是因为无论何时将单元格从视图中滚动出来并向后滚动,都会再次调用cellForRow并将所有内容都设置为默认值,您所要做的就是创build一个正确的数据源,无论何时单元格被检查,您都会更新数据源Bool表示它已被选中,然后将其设置回cellForRowcellWillDisplay