UITableViewCells 中的复选标记显示不正确 [英] Checkmarks in UITableViewCells showing incorrectly
问题描述
我有一个小的可滚动的 tableView,它显示大约八行,当我选择一行时会出现一个复选标记,当我再次选择它时它会消失.
I have a small scrollable tableView which displays roughly eight rows, when I select a row a checkmark appears, when I select it again it disappears.
问题是,当我向下滚动并重复使用单元格时,会自动检查更多行.跟踪哪些行需要复选标记以便不会发生这种情况的最佳做法是什么.我到处找,但没有找到有效的 Swift 解决方案.
The issue is, as I scroll down and the cells are reused, more rows are automatically checked. What is the best practice for tracking which rows require a checkmark so that this does not happen. I have looked everywhere but haven't found Swift solution that works well.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel?.text = "\(searchResults.usernameUserSearchArray[indexPath.row])"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
if selectedCell?.accessoryType == UITableViewCellAccessoryType.Checkmark {
selectedCell?.accessoryType = UITableViewCellAccessoryType.None
} else {
selectedCell?.accessoryType = UITableViewCellAccessoryType.Checkmark
}
tableView.reloadData()
}
推荐答案
这样的事情不适合您吗?我没有测试过,因为我不在 Mac 上.
Wouldn't something like this do it for you? I haven't tested it since I am not on my Mac.
var selectedCells = [NSIndexPath]()
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
cell.accessoryType = selectedCells.contains(indexPath) ? .Checkmark : .None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
selectedCells.append(indexPath)
if selectedCell?.accessoryType == .Checkmark {
selectedCell?.accessoryType = .None
selectedCells = selectedCells.filter {$0 != indexPath}
} else {
selectedCell?.accessoryType = .Checkmark
}
}
这篇关于UITableViewCells 中的复选标记显示不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!