gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:28:13 29 4
gpt4 key购买 nike

我有一个 UITableView,它显示了几个可供用户选择的可用选项。我想要的是让表格始终反射(reflect)所选的选项,这些选项存储在一个数组中,该数组是与 View Controller 的类分开的类的一部分。我试图通过使用 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
}

}

最佳答案

cell.setSelected(true, animated: false)实际上并未选择表格 View 中的单元格。选中单元格后回调。相反,你必须打电话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)
}
}

关于ios - UITableViewCell 在实现 willDisplay 函数时不取消选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53587360/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com