UITableViewCells中的选中标记显示不正确

Ben*_*van 0 uitableview ios swift

我有一个小的可滚动tableView,它显示大约8行,当我选择一行时出现一个复选标记,当我再次选择它时它会消失.

问题是,当我向下滚动并重复使用单元格时,会自动检查更多行.跟踪哪些行需要选中标记以便不会发生这种情况的最佳做法是什么.我到处都看,但没有找到效果很好的Swift解决方案.

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()
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*uke 6

这样的事情会不适合你呢?我没有测试它,因为我不在我的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
    }
}
Run Code Online (Sandbox Code Playgroud)