swift 3 - ViewController没有取消选择UITableView中的选定行

时间:2017-02-28 21:34:17

标签: ios uitableview swift3

我有一个tableview,用户可以在其中选择多行(这些行由行中的复选框区分)。但是,出于某种原因,我无法实现取消选择任何选定行的功能。有人能告诉我我错过了什么吗?

SomeViewController.m

@objc class SomeViewController: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate {

    var deviceArray:[Device] = []

    // [perform a fetch]
    // [insert fetch results into deviceArray to be displayed in the tableview]

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "customcell", for:
        indexPath)

        // Set up the cell
        let device = self.deviceArray[indexPath.row]
        cell.textLabel?.text = device.name

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView(tableView, cellForRowAt: indexPath).accessoryType = UITableViewCellAccessoryType.checkmark
        NSLog("Selected Row")
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        self.tableView(tableView, cellForRowAt: indexPath).accessoryType = UITableViewCellAccessoryType.none
        NSLog("Deselected Row")
    }
}

更多信息: 查看插入的调试日志,我可以分享以下观察结果:

  1. 选择未选择的行时,控制台会打印“Selected Row”

  2. 如果我点击观察#1中的同一行,控制台只打印“选定行”

  3. 如果我点击任何其他行,控制台会打印“取消选择行”,然后打印“选定行”

  4. 如果我点击与观察#3相同的行,则控制台仅打印“选定行”。

  5. 因此,看起来每次我点击不同的行时,tableView:didDeselectRowAt:被调用;但是,点击的行中的复选标记不会消失。

    更多信息2:

    所以我是故事板的新手,并没有设置“allowsMultipleSelection”属性。进入属性检查器,这就是我的设置:

    enter image description here

    现在,当在tableView中按下同一行时,我的控制台确认应用程序在tableView:didSelectRowAt:和tableView:didDeselectRowAt:之间交替,但是,复选标记不会消失;一旦用户选择了一行,即使调用了tableView:didDeselectRowAt:,复选标记仍保持选中状态。我还缺少什么?

2 个答案:

答案 0 :(得分:2)

首先,如果您从故事板设置数据源和委托出口,请确保已设置。

enter image description here

另一件事是你需要将allowsMultipleSelection属性设置为true才能获得所需行为的didSelectdidDeselect方法。否则,它将始终为您点按的单元格调用didSelect,并为最先选择的单元格调用didDeselect

另一件需要注意的是,在设置self.tableView属性时,您正在引用cell.accessoryType。这可能是传递给委托方法的tableView的不同实例。我建议使用guard let语句,以确保代码设置附件类型仅适用于传递给函数的tableView。这是我用来使它工作的代码。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Notice I use tableView being passed into func instead of self.tableView
    guard let cell = tableView.cellForRow(at: indexPath) else {
        return
    }
    cell.accessoryType = .checkmark

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    guard let cell = tableView.cellForRow(at: indexPath) else {
        return
    }
    cell.accessoryType = .none
}

答案 1 :(得分:0)

如果您希望用户能够选择多个单元格,则需要在tableView.allowsMultipleSelection = true方法中设置viewDidLoad或在属性检查器中设置多个选择。

相关问题