본문 바로가기

iOS 앱 개발자 프로젝트/iOS 입문

[iOS] 메모 앱 만들기 Day-3

2024년 3월 22일 금요일

 

Todo List 화면 만들기 (TodoListViewController)


 

오늘도 어김없이 ViewController와 EntryViewController를 오가며 

build fail 앞에서 가지각색 오류들을 경험했는데, 

 

"Declaration is only valid at file scope"  { } 를 깜빡하거나 위치를 잘못 잡은 경우 쉽게 해결되는 오류였다. 

 

beginners 수준이 이정도라니 ...

주말에 다시 한번 review 해야겠다. 아자아자! ... 

 

 

 

 

ViewController ▽

import UIKit



class ViewController: UIViewController {
    
    
    @IBOutlet var tableView: UITableView!
    
    var tasks = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "Tasks"
        
        tableView.delegate = self
        tableView.dataSource = self
        
        // Setup
        
        if !UserDefaults().bool(forKey: "setup") {
            UserDefaults().set(true, forKey: "setup")
            UserDefaults().set(0, forKey: "count")
        }
        
        // Get all current saved tasks
        updateTasks()
    }
    
    func updateTasks() {
        
        tasks.removeAll()
        
        guard let count = UserDefaults().value(forKey: "count") as? Int else {
            return
        }
        
        for x in 0..<count {
            
            if let task = UserDefaults().value(forKey: "task_\(x+1)") as? String {
                tasks.append(task)
            }
        }
        
        tableView.reloadData()
        
    }
    
    
    
    @IBAction func didTapAdd() {
        
        let vc = storyboard?.instantiateViewController(identifier:"entry") as! EntryViewController
        vc.title = "New Task"
        vc.update = {
            DispatchQueue.main.async {
                self.updateTasks()
            }
        }
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
}
    

    extension ViewController: UITableViewDelegate {
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
        }
        
    }
    
    extension ViewController: UITableViewDataSource {
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return tasks.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            
            cell.textLabel?.text = tasks[indexPath.row]
            
            return cell
        }
    }