У меня есть 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
}
}