实现 willDisplay 函数时 UITableViewCell 不取消选择

mig*_*now 4 uitableview ios swift

我有一个UITableView显示几个可用选项供用户选择的窗口。我想要的是表始终反映所选的选项,这些选项存储在一个数组中,该数组是与视图控制器分开的类的一部分。我试图使用该方法在加载表时显示选定的选项tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)。我遇到的问题是,当我实现此方法时,加载表时数组中的任何选项在按下时都不会取消选择。代码如下:

class Options {
    enum Option : String {
        case option1 = "Option 1"
        case option2 = "Option 2"
        case option3 = "Option 3"
        case option4 = "Option 4"
        case option5 = "Option 5"
        case option6 = "Option 6"
        case option7 = "Option 7"
    }
    static let allOptions : [Option] = [.option1, .option2, .option3, .option4, .option5, .option6, .option7]
    static var selectedOptions : [Option] = [.option2, .option7]
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var optionsTableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Options.allOptions.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = Options.allOptions[indexPath.row].rawValue
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        Options.selectedOptions.append(Options.allOptions[indexPath.row])
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let option = Options.allOptions[indexPath.row]
        for o in Options.selectedOptions {
            if option == o {
                let i = Options.selectedOptions.index(of: o)!
                Options.selectedOptions.remove(at: i)
            }
        }
    }

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let option = Options.allOptions[indexPath.row]
        if Options.selectedOptions.contains(option) {
            cell.setSelected(true, animated: false)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.optionsTableView.allowsMultipleSelection = true
        self.optionsTableView.delegate = self
        self.optionsTableView.dataSource = self
    }

}
Run Code Online (Sandbox Code Playgroud)

Enk*_*dal 5

cell.setSelected(true, animated: false)实际上并没有选择表格视图中的单元格。这是选择单元格后的回调。相反,你必须打电话 tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)

你的 willDisplay 函数应该是:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    let option = Options.allOptions[indexPath.row]
    if Options.selectedOptions.contains(option) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }
}
Run Code Online (Sandbox Code Playgroud)