1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import UIKit
class TodoListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! private var viewModel: TodoListViewModel! private var cancellables = Set<AnyCancellable>() override func viewDidLoad() { super.viewDidLoad() setupViewModel() setupTableView() setupNavigationBar() } private func setupViewModel() { let context = (UIApplication.shared.delegate as! AppDelegate) .persistentContainer.viewContext viewModel = TodoListViewModel(context: context) viewModel.$todos .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.tableView.reloadData() } .store(in: &cancellables) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } private func setupNavigationBar() { title = "待办事项" navigationItem.rightBarButtonItem = UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(addTodo) ) } @objc private func addTodo() { let alert = UIAlertController(title: "新任务", message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.placeholder = "输入任务内容" } let addAction = UIAlertAction(title: "添加", style: .default) { [weak self] _ in guard let text = alert.textFields?.first?.text, !text.isEmpty else { return } self?.viewModel.addTodo(title: text) } alert.addAction(addAction) alert.addAction(UIAlertAction(title: "取消", style: .cancel)) present(alert, animated: true) } }
extension TodoListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.todos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let todo = viewModel.todos[indexPath.row] cell.textLabel?.text = todo.title cell.accessoryType = todo.isCompleted ? .checkmark : .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let todo = viewModel.todos[indexPath.row] viewModel.toggleComplete(todo) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let todo = viewModel.todos[indexPath.row] viewModel.deleteTodo(todo) } } }
|