[240110] Today I Learned

YoungHyun Kim·2024년 1월 10일
1

TIL ✍️

목록 보기
33/68

1. TableViewCell 갱신, 삭제와 동시에 데이터를 올바르게 업데이트 하기

새로운 To Do를 삽입하는데, 이런 에러가 발생했다.

내가 새로운 Todo를 삽입하는 방법은, 화면 우측 상단에 + 버튼을 누르면

이런 Alert 창이 나오고, 내용과 카테고리를 입력하면 tableView reloadData()를 해줘야되는데 그러지 못해서 나오는 오류였다.

@IBAction func addTodo(_ sender: Any) {
        let alertForAddTodo = UIAlertController(title: "Todo 추가", message: nil, preferredStyle: .alert)
        alertForAddTodo.addTextField{ textField in
            textField.placeholder = "내용을 입력하세요."
        }
        alertForAddTodo.addTextField{ textField in
            textField.placeholder = "카테고리를 입력하세요."
        }
        
        let confirmAction = UIAlertAction(title: "추가", style: .default){ [weak self] _ in
            guard let self else { return }
            if let title = alertForAddTodo.textFields?[0].text, !title.isEmpty, let cat = alertForAddTodo.textFields?[1].text, !cat.isEmpty {
                let newItem = Todo(id: (todoList.last?.id ?? -1) + 1, title: title, isCompleted: false, category: cat)
                todoList.append(newItem)
                if sections.keys.contains(cat) {
                    sections[cat]?.append(newItem)
                } else {
                    sections[cat] = [newItem]
                }
                userDefault.set(title, forKey: "\(newItem.id)")
                TodoTableView.reloadData()
            } else {
                let missingTitleAlert = UIAlertController(title: "내용이 모두 입력되지 않았습니다.", message: "빈 칸이 있는지 확인하십시오.", preferredStyle: .alert)
                let confirm = UIAlertAction(title: "확인", style: .default)
                missingTitleAlert.addAction(confirm)
                present(missingTitleAlert, animated: true)
            }
        }
        let rejectAction = UIAlertAction(title: "취소", style: .cancel)
        alertForAddTodo.addAction(confirmAction)
        alertForAddTodo.addAction(rejectAction)
        present(alertForAddTodo, animated: true)
    }

위에처럼, Alert 창의 "추가" 버튼을 눌렀을 때, TodoTableView.reloadData() 메서드를 호출해서 해결!

profile
iOS 개발자가 되고 싶어요

0개의 댓글