|
| 1 | +#ViewController Transition |
| 2 | + |
| 3 | +##1. ??? |
| 4 | +```swift |
| 5 | + @IBAction func doneButtonDidTap() { |
| 6 | + if let title = self.titleInput.text, !title.isEmpty { |
| 7 | + let newTask = Task(title: title) |
| 8 | + |
| 9 | + //자기 자신을 띄운 컨트롤러를 가져온다 -> 네비게이션 뷰 컨트롤러 |
| 10 | + if let navigationContoller = self.presentingViewController as? UINavigationController { |
| 11 | + //네비게이션 뷰 컨트롤러가 가지고 있는 가장 첫 번째 뷰 컨트롤러를 가져온다. |
| 12 | + if let taskListViewController = navigationContoller.viewControllers.first as? TaskListViewController { |
| 13 | + taskListViewController.tasks.append(newTask) |
| 14 | + taskListViewController.tableView.reloadData() |
| 15 | + self.dismiss(animated: true, completion: nil) |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | +``` |
| 21 | + |
| 22 | +##2. Delegate |
| 23 | +#### Task Edit View Controller |
| 24 | +```swift |
| 25 | +class TaskEditViewController: UIViewController { |
| 26 | + |
| 27 | + @IBOutlet var titleInput: UITextField! |
| 28 | + |
| 29 | + weak var delegate: TaskEditViewControllerDelegate? //강한 참조 대신 약한 참조, weak은 참조타입에만 쓸 수 있다. |
| 30 | + |
| 31 | + override func viewDidAppear(_ animated: Bool) { |
| 32 | + super.viewDidAppear(animated) |
| 33 | + self.titleInput.becomeFirstResponder() |
| 34 | + } |
| 35 | + |
| 36 | + @IBAction func doneButtonDidTap() { |
| 37 | + if let title = self.titleInput.text, !title.isEmpty { |
| 38 | + |
| 39 | + self.delegate?.taskEditViewController(self, didAddTask: newTask) |
| 40 | + self.dismiss(animated: true, completion: nil) |
| 41 | + |
| 42 | + } |
| 43 | + } |
| 44 | + //... |
| 45 | +} |
| 46 | + |
| 47 | +// MARK: - TaskEditViewControllerDelegate |
| 48 | + |
| 49 | +protocol TaskEditViewControllerDelegate: class { //: class 는 참조타입에만 적용된다는 표시 |
| 50 | + |
| 51 | + func taskEditViewController(_ taskEditViewController: TaskEditViewController, didAddTask task: Task) |
| 52 | + |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +#### Task List View Controller |
| 57 | +```swift |
| 58 | +class TaskListViewController: UIViewController { |
| 59 | + //... |
| 60 | + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { |
| 61 | + if let navigationController = segue.destination as? UINavigationController, |
| 62 | + let taskEditViewController = navigationController.viewControllers.first as? TaskEditViewController { |
| 63 | + |
| 64 | + taskEditViewController.delegate = self |
| 65 | + |
| 66 | + } |
| 67 | + } |
| 68 | + //... |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +##3. Closure |
| 73 | + |
0 commit comments