我有一个待办事项列表应用程序,当用户点击任务时,我想在右侧显示一个复选标记(表示任务已完成)。这是TableViewController的代码:
import UIKit
class LoLFirstTableViewController: UITableViewController {
var tasks:[Task] = taskData
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 60.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
@IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) {
}
@IBAction func saveAddTask(_ segue:UIStoryboardSegue) {
if let AddTaskTableViewController = segue.source as? AddTaskTableViewController {
if let task = AddTaskTableViewController.task {
tasks.append(task)
let indexPath = IndexPath(row: tasks.count-1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
let task = tasks[indexPath.row]
cell.task = task
if task.completed {
cell.accessoryType = UITableViewCellAccessoryType.checkmark;
} else {
cell.accessoryType = UITableViewCellAccessoryType.none;
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
var tappedItem = tasks[indexPath.row] as Task
tappedItem.completed = !tappedItem.completed
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}
}
当我运行它时,单击任务时没有任何反应。我在这里错过了什么?不幸的是,我的斯威夫特的能力还有很多不足之处。任何帮助将不胜感激,谢谢!
供参考,以下是任务类的代码:
import UIKit
struct Task {
var name: String?
var points: Int
var completed: Bool
init(name: String?, points: Int, completed: Bool = false) {
self.name = name
self.points = points
self.completed = completed
}
}
答案 0 :(得分:1)
问题在于您更新任务的didSelectRowAt
方法。 struct
是值类型。任何更改通常都会生成新副本。数组也是值类型。因此,当您更新tappedItem
变量时,最终会得到一个新任务副本,但数组中的那个副本实际上并未更新。因此,当重新加载单元格时,未修改的任务用于设置单元格。
按如下方式更新您的代码:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
var tappedItem = tasks[indexPath.row] as Task
tappedItem.completed = !tappedItem.completed
tasks[indexPath.row] = tappedItem // add this line
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}