4
4
### Protocol Oriented Swift
5
5
### Delegate
6
6
7
- **Problem:** Communicate between classes and structs
7
+ **Problem:** How does delegate even work?
8
8
9
9
---
10
10
*/
11
- //: Delegate
12
- //: 1. A gift from Apple engineers
13
- //: 2. microwave analogy
11
+
12
+ //: > **Purpose of Delegate:** Communicate between objects
13
+
14
+
15
+ //: **Goal:** Send data from `FirstVC` to `SecondVC`
14
16
15
17
//: Design Protocol
16
18
protocol PassDataDelegate {
@@ -20,16 +22,17 @@ protocol PassDataDelegate {
20
22
21
23
//: Design Delegator (Sender)
22
24
class FirstVC {
25
+ func drawCircle( ) { }
23
26
var delegate : PassDataDelegate ?
24
27
}
25
28
26
- FirstVC ( ) . delegate? . passData ( data: " Bob " )
29
+ FirstVC ( ) . delegate? . passData ( data: " A bunch of contracts " )
27
30
28
31
29
32
//: Design Delegate (Receiver)
30
33
class SecondVC : PassDataDelegate {
31
34
func passData( data: String ) {
32
- print ( " Something happened " )
35
+ print ( " The CEO gave me \( data ) " )
33
36
}
34
37
}
35
38
@@ -40,17 +43,32 @@ let secondVC = SecondVC()
40
43
41
44
//: Assign Delegate
42
45
firstVC. delegate = secondVC
43
- firstVC. delegate? . passData ( data: " Hello, 1231231 " )
44
-
46
+ firstVC. delegate? . passData ( data: " A bunch of contracts " )
45
47
46
48
47
49
48
50
51
+ //: Practical Example in iOS
52
+ import UIKit
49
53
54
+ class BobViewController : UIViewController , UITableViewDelegate {
55
+ let tableView = UITableView ( )
56
+ override func viewDidLoad( ) {
57
+ super. viewDidLoad ( )
58
+ tableView. delegate = self
59
+ }
60
+
61
+ func tableView( _ tableView: UITableView , didSelectRowAt indexPath: IndexPath ) {
62
+ print ( indexPath)
63
+ }
64
+ }
50
65
51
66
67
+ //: tableView.delegate.tableView(_ tableView: UITableView, didSelectRorwAt indexPath: IndexPath)
52
68
53
69
70
+ // UITableView is the delegator/CEO/sender
71
+ // BobViewController is the delegate/Secretary/receiver
54
72
55
73
56
74
0 commit comments