我试图从我的tableView中的选定行中获取数据。我会将选定的行追加到数组中,这确实很有用。不幸的是,当我取消选择该行并再次选择它时,它会再次追加它。我需要编写一些逻辑来从数组中删除取消选择的行。
有谁知道我该怎么做?
以下是选择行时的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
selectedCell?.contentView.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
rowSelected+=1
if rowSelected >= 1 {
nextBtn.isEnabled = true
nextBtn.backgroundColor = UIColor(red: 84.0 / 255, green: 199.0 / 255, blue: 252.0 / 255, alpha: 1)
}
let exercisesSelected = selectedCell?.exerciseNameLbl.text
exerisenames.append(exercisesSelected!)
print(exerisenames)
}
以下是取消选择行的代码:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
selectedCell?.textLabel?.textColor = UIColor.darkGray
rowSelected-=1
if rowSelected == 0 {
nextBtn.isEnabled = false
nextBtn.backgroundColor = UIColor.darkGray
nextBtn.setTitle("Choose an exercise", for: UIControlState.disabled)
}
let exercisesDeselected = selectedCell?.exerciseNameLbl.text
if exerisenames.contains(exercisesDeselected!) {
print("exercise already in the row and has to be deleted before going further")
}
print(exerisenames)
}
两者都将引用我在顶部创建的数组:exercisenames
答案 0 :(得分:0)
通过快速查看文档,您可能需要类似
的内容if let index = exercisenames.index(of: exercisesDeselected) {
exercisenames.remove(at: index)
}
但我也认为@ almas对有序集合的建议可能会很好。