The Basics of Creating a Mac Program
Whatever type of OS X program you want to create, such as a video game or a custom program for lawyers or stock brokers, you’ll always go through the same basic steps. First, you need to create an OS X project. This creates a bare-bones OS X program that includes a generic user interface.
Second, you’ll need to customize this generic OS X program in two ways: by adding items to the user interface and by writing Swift code to make the program actually do something.
Third, you’ll need to run and test your program. After running and testing your program, you’ll likely need to constantly go back and modify your user interface or Swift code to fix problems and add new features. Eventually your program will reach a point where it’s complete (for now) and you can ship it. Then you’ll repeat these basic steps all over again to add new features once more.
Generally you’ll spend more time modifying a program than creating new ones. However, it’s useful to create small programs to test out different features. Once you get these smaller, experimental programs working, you can add them to another program. By doing this, you don’t risk messing up a working program.
Creating a Project
The first step to creating a program is to create a new project. When you create a project, Xcode gives you the option of choosing different templates, which provides basic functions. All you have to do is customize the template. The four categories of OS X templates are shown in Figure 3-1:
Figure 3-1. The four categories of OS X templates for creating a project
Most of the time you’ll choose a template in the Application category, and the most common template is Cocoa Application, which creates a standard OS X program with pull-down menus and a window.
The other two Application templates are Game (for creating video games) and Command Line Tool (for creating programs that don’t need a traditional graphical user interface).
The Framework & Library category is meant to create reusable software libraries. The System Plug-in category is meant to create plug-ins for other type of programs. The Other category is meant for creating programs that don’t fit into the other categories.
For the purposes of this book, we’ll always use the Cocoa Application under the OS X Application category. The other OS X categories are designed for advanced programmers and won’t be covered in this book.
When you create a Cocoa Application project, you’ll need to define several items as shown in Figure 3-2:
Figure 3-2. Defining a Cocoa Application project
Your product’s name is completely arbitrary but should be descriptive since Xcode will store all your files in a folder using your chosen name.
Your organization name and identifier are also arbitrary and are typically assigned from your Apple Developer account. Both of these can also be arbitrary strings if you want, but if you plan on distributing your programs through the Mac App Store, they should be linked to your Apple Developer account.
The Language pop-up menu lets you choose Objective-C or Swift. For the purposes of this book, you always want to choose Swift. Objective-C is a more complicated programming language that Apple still supports, but it’s no longer considered Apple’s official programming language.
The Use Storyboards check box lets you create a user interface that either consists of a single window (a .xib file) or a series of windows linked together (a .storyboard file). We’ll go over both methods for creating a user interface, but unless instructed otherwise, leave the Use Storyboards check box empty. That’s because storyboards are more complicated to use.
The Create Document-Based Application means that Xcode creates a Cocoa Application that can open and manage multiple windows, such as the multiple windows available in a word processor. Managing multiple windows is more complicated so leave the Create Document-Based Application check box empty for now.
The Use Core Data check box lets you store data typically for database applications such as saving lists of names and addresses. Leave this check box blank since this is for more advanced OS X programs.
Ready to create your first OS X program? Then follow these steps:
Figure 3-3. The Welcome to Xcode opening screen
Figure 3-4. The MyFirstProgram running
Without doing a thing, you managed to create a program that looks and behaves like a typical Macintosh program. Of course, this bare-bones Macintosh program won’t do anything interesting until you customize the user interface and write Swift code to make the program do something useful.
Designing a User Interface
When designing a user interface, keep in mind the three purposes for any user interface:
When you design a user interface, every element must satisfy one of these criteria. Colors and lines might just seem decorative, but they can be useful to organize a user interface so users will know where to find information, how to input data, or how to give commands to the program.
To create a user interface in Xcode, you need to follow a two-step process:
To see how to use the Object Library, let’s add a label, a text field, and a button to the MyFirstProgram user interface. The label will display text to the user; the text field will let the user type in data; and the button will make the program take the text from the text field, modify it by capitalizing every character, and place the modified uppercase text into the label.
To do this, follow these steps:
Figure 3-5. The MyFirstProgram icon displays the MyFirstProgram user interface
Figure 3-6. Using blue guidelines to place a Push Button near the bottom of the MyFirstProgram window
Figure 3-7. Typing in the search field helps you easily find items in the Object Library
Figure 3-8. A label, text field, and button on the MyFirstProgram user interface
At this point, you’ve customized the generic user interface. Now you have to customize each user interface item using the Inspector pane. Through the Inspector pane, you can choose different options for a user interface item, such as typing the exact width of a button or choosing a background color for a text field.
When resizing or moving an item on the user interface, you can either type exact values into the Size Inspector pane, or you can just drag the mouse to resize or move an item. Either way is acceptable but the Size Inspector pane gives you precise control over items. Let’s see how to use the Inspector pane to customize our generic user interface.
Figure 3-9. The Attributes Inspector pane lets you customize the appearance of items
Figure 3-10. The Width text field appears in the Size Inspector pane
Figure 3-11. Using blue guidelines to center items on the user interface
At this point, you’ve customized the appearance of your user interface. If you run this program, the user interface will look good but it won’t actually do anything. To make a user interface work, you need to finish two more steps:
You need to write Swift code to make your program calculate some useful result. You also need to connect your user interface to your Swift code so you can retrieve data from the user interface and display information back on the user interface.
In this example, we’ll write Swift code that retrieves text from the text field, changes it to uppercase, then displays the uppercase text back on to the label when the user clicks the Change Case push button.
So we need to write Swift code that converts text to uppercase. Then we need to connect the text field and the label so the Swift code can retrieve data from the text field and put new data on the label.
To send or retrieve data from a user interface item so Swift code can access it, we need to use something called an IBOutlet. An IBOutlet essentially represents a user interface item (such as a label or a text field) as a variable that Swift code can use.
To help you create an IBOutlet, use the Assistant Editor. The Assistant Editor lets you display the user interface in one pane and your Swift code in an adjacent pane. Then you can use the mouse to drag between your user interface items to your Swift code to create an IBOutlet that connects the label or text field to an IBOutlet. Let’s see how that works:
Figure 3-12. The Assistant Editor lets you view the user interface and Swift code file side by side
Figure 3-13. Control-dragging creates a connection between a user interface item and your Swift code
Figure 3-14. A pop-up window lets you define a name for your IBOutlet
@IBOutlet weak var labelText: NSTextField!
@IBOutlet weak var messageText: NSTextField!
Let’s go over what you just did. First, you created an IBOutlet to represent the label and the text field. The label is now represented by the name “labelText,” and the text field is now represented by the name “messageText.” Now when your Swift code wants to store or retrieve data from the label or text field, it can just refer to them by the names “labelText” or “messageText.”
Second, you created a link between your Swift code and your user interface items. Now your Swift code can send and retrieve data to the label and text field on your program’s user interface.
Connecting your user interface to your Swift code is a major step toward making your user interface actually work. However, we need to make the Change Case button do something when the user clicks on it. To do that, we need to create something called an IBAction method.
Where an IBOutlet lets Swift code send or retrieve data from a user interface item, an IBAction method lets a user interface item run Swift code that does something. In this case, we want the user to type text into the text field. Then the program will take that text, capitalize it, and display this capitalized text back into the label.
To do this, we need to know how to do the following:
Storing and retrieving text from a text field and label is similar because both are defined by IBOutlet variables. Let’s take a look at what these IBOutlets mean:
@IBOutlet weak var labelText: NSTextField!
@IBOutlet weak var messageText: NSTextField!
All user interface items in the Object Library are based on class files, which make up the Cocoa framework. In this case, we created two IBOutlet variables called labelText and messageText, which are both based on the NSTextField class file.
If you look up the NSTextField class file in Xcode’s documentation, you’ll see a long list of all the properties that anything based on the NSTextField can hold. However, you won’t find anything that describes the property that holds text.
However, if you remember from Chapter 1, object-oriented programming means that class files can inherit from other class files. In this case, the NSTextField class inherits from another class called NSControl. Looking up NSControl in Xcode’s documentation (which you’ll learn how to do in the next chapter), you can see that NSControl has a property that holds text called stringValue as shown in Figure 3-15.
Figure 3-15. Xcode’s documentation shows the NSControl property for holding text
To access text stored in the text field, we need to identify the text field by name (messageText) and its property that holds the text (stringValue) such as:
messageText.stringValue
To display text in the label, we need to identify the label by name (labelText) and its property that holds text (stringValue) such as:
labelText.stringValue
Now the next question is how can we capitalize text? Swift stores text in a data type called String, which is based on a class called NSString . (How would you know this? You have to understand the Cocoa framework, which you’ll learn more about in Chapter 4.) The NSString class has a method called uppercaseString as shown in Figure 3-16.
Figure 3-16. Xcode’s documentation shows the NSString class has a method for capitalizing text called uppercaseString
To capitalize the text stored in the text field (represented by the IBOutlet name messageText, we just have to apply the uppercaseString method on the IBOutlet’s text property like this:
messageText.stringValue.uppercaseString
This Swift code says take the messageText object (which is the text field on the user interface), retrieve the text it contains (which is in the stringValue property), and apply the uppercaseString method on this text.
Now that we know how to retrieve text from the text field, capitalize it, and store new text back into the label, the last step is to write the code that does all this inside an IBAction method. This IBAction method needs to run each time the user clicks the Change Case button. That means we need to create an IBAction method and link it to the Change Case button.
Figure 3-17. Control-dragging from the button to the AppDelegate.swift file
Figure 3-18. Creating an Action connection
@IBAction func changeCase(sender: NSButton) {
}
Figure 3-19. Choosing a Type for an IBAction method
At this point, you’ve created an IBAction method that runs every time the user clicks the Change Case button. Of course, there’s no Swift code inside that IBAction, so now we need to type Swift code inside those curly brackets that define the beginning and ending of the IBAction method.
@IBAction func changeCase(sender: NSButton) {
labelText.stringValue = messageText.stringValue.uppercaseString
}
Figure 3-20. Running the MyFirstProgram
As you can see, you created a simple Macintosh program without writing much Swift code at all. The Swift code you did write was just a single line that took the text stored in the text field, changed it to uppercase, and then stored this uppercase text in the label.
Much of the power of Swift comes from relying on Apple’s Cocoa framework as much as possible. That means you have to understand object-oriented programming and how classes define properties (to store data) and methods (to manipulate data) – and use inheritance – which you’ll learn more about in the next chapter.
The main point is to see how Xcode creates generic OS X programs so you just need to design and customize the user interface, then write Swift code to make it all work.
Using the Document Outline and Connections Inspector
Before we conclude this short introduction to creating your first Macintosh program, let’s look at two other items that will prove helpful when working with Xcode in the future: the Document Outline and the Connections Inspector.
The Document Outline lists all the items that make up your user interface. To open or hide the Document Outline, you can do the following as shown in Figure 3-21:
Figure 3-21. The Document Outline
The Document Outline makes it easy to select different items on your user interface. In our MyFirstProgram, there’s only three items (a label, text field, and button), but in more complicated user interfaces, you could have many more items that could be hidden behind other items or too small to see easily.
If you click on an item in the Document Outline, Xcode selects that item in the user interface (and vice versa) as shown in Figure 3-22.
Figure 3-22. Clicking on an item in the Document Outline window selects that item on the user interface
Think of the Document Outline as a fast way to see all the parts of a user interface and select just the items you want.
Once you start connecting user interface items to your Swift code through IBOutlets and IBAction methods, you may wonder what items are connected to which IBOutlets and IBAction methods. To see the connections between IBOutlets/IBAction methods and user interface items, you have two options.
First, you can use the Connections Inspector . Second, you can use the Assistant Editor.
To open the Connections Inspector, first click on any item in the user interface that you want to examine, and then do one of the following to display the Connections Inspector that appears in the upper right corner of the Xcode window as shown in Figure 3-23:
Figure 3-23. The Connections Inspector shows all the connections to the currently selected user interface item
The Connections Inspector shows the Swift file that holds an IBOutlet or the IBAction method connected to the selected user interface item.
Note If you look carefully, the Connections Inspector displays an X to the left of the Swift file that links to the currently selected user interface item. If you click on this X, you can break the link between a user interface item and its IBOutlet or IBAction method.
Another way to see way to see which IBOutlets and IBAction methods are connected to user interface items is to open the user interface (such as clicking on the MainMenu.xib file) and then opening the Assistant Editor.
To the left of each IBOutlet and IBAction method in your Swift file, you’ll see a gray circle. When you move the mouse pointer over a gray circle, Xcode highlights the user interface item that’s connected to that IBOutlet or IBAction method as shown in Figure 3-24.
Figure 3-24. The Assistant Editor lets you see which IBOutlet and IBAction methods are connected to user interface items
Summary
Xcode is the only program you need to design, write, and modify your own OS X programs. When you want to create an OS X program, you’ll follow the same basic steps:
To design your user interface, you need to drag and drop items from the Object Library. Then you need to use the Attributes and Size Inspector to customize each user interface item. To help you select user interface items, you can use the Document Outline.
After designing your user interface, you need to connect your user interface to your Swift code through IBOutlets (for retrieving or displaying data) and IBAction methods (to make your user interface do something) using the Assistant Editor.
To review the connections between your user interface items and your Swift code, you can use the Connections Inspector or the Assistant Editor.
Already you can see how the different parts of Xcode work to help you create a program, and we still haven’t explored many other Xcode features yet. Perhaps the most confusing part about creating a Macintosh program can be writing Swift code and using methods stored in the class files that make up the Cocoa framework, so the next chapter will explain this in more detail.
As you can see, using Xcode is actually fairly simple once you focus only on those features you actually need and ignore the rest. As we go through each chapter, you’ll keep learning a little more about Xcode and Swift programming.
Already you’ve learned so much about Xcode, and yet you’ve only just begun.