Pages

Saturday, 29 April 2017

Delegates are responders that acts to events that occurs in a program. AppKit delegates often work with Cocoa UI events. Here we will see two examples of handling events, one for NSTextField and another for NSTextView in conjunction with Interface Builder, rather than programatically.

1. Create a macOS Cocoa project from Xcode which will generate an AppDelegate and a ViewController as usual.
2. We will make the ViewController as the delegate to respond to events. For that we need to declare that the ViewController adopts the formal protocol defined by the delegates.

3. Choose the Main.storyboard and choose the View Controller Scene, drag and drop Text View and Text Field components.
4. Choose the Text View from the Document Outline of the View Controller Scene, option click, and in the popup, connect the delegate outlet to the View Controller. Same for Text Field.
5. Now, in the ViewController.h header, declare two IBOutlets which will connect the components in the storyboard to the code.

Since these interface builder outlets are not connected yet, the radio box is in unchecked state.
6. Go back to the interface builder (the storyboard file), choose Text View, option click, drag and connect the New Referencing Outlet to View Controller which brings the above IBOutlets. Choose textView to make the connection. Do the same for Text Field, but here we should choose textField as the referencing outlet.
7. Back to code, open ViewController.m implementation file and implement any of the delegated methods.