This is a series of articles explaining how to create a Cocoa version of Hello World. In this article, we create a window class and make it a window controller of the Hello World window.
This article utilizes the sample code created in the previous article. If you don’t have it, download it from the previous article.
What is a window controller?
AppKit uses a window and its window controller to control windows displayed in the app. First, open the Main.storyboard
file.
Pay attention to the area circled in the screen capture. It contains the following three scenes.
- Application Scene
- Window Controller Scene
- View Controller Scene
A scene that is explained in this article is Window Controller Scene. By opening the Window Controller Scene disclosure button, you can find the Window Controller. Then, open the disclosure button of the Window Controller. You will find the window.
As mentioned above, the Window Controller manages the window, and the Window Controller Scene manages the Window Controller.
Select the Window Controller Scene and see the attributes inspector. The “Is Initial Controller” option is on. The Window Controller Scene, which the “Is Initial Controller” option is on, will be used first when its storyboard file is loaded.
Upon loading the Main.storyboard
, the Window Controller scene is used. Next, the window controller, which is managed by the scene, is loaded. Finally, the window managed by the Window Controller is displayed.
Add the window controller
In AppKit, the window controller class is the NSWindowController
class. When the window is operated, or its state is changed, the AppKit uses call methods of NSWindowController
or delegate of NSWindowController
.
When you create the AppKit app, you create the subclass of the NSWindowController
class to implement your window controller class.
Let’s implement a window controller class for Cocoa Hello World.
Add a class
Add a class to the project. Do as follows.
You can also select the “Swift File”. The only difference lies in the generated code.
Enter as follows and click the “Next” button.
設定項目 | 説明 |
---|---|
Class |
HelloWindowController
|
Subclass of |
NSWindowController
|
Also create XIB file for user interface | Off |
Language | Swift |
import Cocoa
class HelloWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
Change the class of the instance
When the Main.storyboard
is loaded and the Window Controller Scene is displayed, AppKit instantiates the NSWindowController
class.
Replace the NSWindowController
class with the HelloWindowController
class. Do following.
Now, the HelloWindowController
class becomes the instantiation class.
Download the sample code
You can download the sample code created in this article here.