Chapter    3

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:

  • Application
  • Framework & Library
  • System Plug-in
  • Other

9781484212349_Fig03-01.jpg

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:

  • The name of your product
  • The programming language to use (Objective-C or Swift)
  • Whether to use storyboards or not for your user interface
  • Whether to create a document-based application
  • Whether to use Core Data

9781484212349_Fig03-02.jpg

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:

  1. Start Xcode. If a Welcome to Xcode screen appears as shown in Figure 3-3, click Create a new Xcode project. If this welcome screen does not appear, choose File image New image Project or choose Window image Welcome to Xcode to display this screen so you can choose Create a new Xcode project. Xcode displays a list of project templates (see Figure 3-1).

    9781484212349_Fig03-03.jpg

    Figure 3-3. The Welcome to Xcode opening screen

  2. Click Application under the OS X category. A list of different OS X Application templates appears.
  3. Click Cocoa Application and then click the Next button. Xcode now asks for your project name (see Figure 3-2).
  4. Click in the Product Name text field and type MyFirstProgram.
  5. Click in the Language pop-up menu and make sure Swift appears.
  6. Make sure all check boxes are empty and then click the Next button. Xcode now asks where you want to store your project.
  7. Click on a folder where you want to store your Xcode project and click the Create button. Congratulations! You’ve just created your first OS X program. At this point, Xcode just created a generic Macintosh program, but you haven’t had to write a single line of Swift code or even design the user interface to create an actual working program.
  8. Choose Product image Run, press Command+R, or click the Run icon. Xcode runs your program called MyFirstProgram as shown in Figure 3-4. Notice that the MyFirstProgram displays a menu bar with pull-down menus and a window that you can move or resize on the screen. Because you used the Cocoa Application template, Xcode automatically created all the code necessary to create a generic Macintosh program.

    9781484212349_Fig03-04.jpg

    Figure 3-4. The MyFirstProgram running

  9. Choose MyFirstProgram image Quit MyFirstProgram. Xcode appears. Keep your MyFirstProgram project open in Xcode for the next section.

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:

  • To display information to the user
  • To get data from the user
  • To let the user give commands to the program

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:

  • Use the Object Library to drag and drop items on to your user interface
  • Use the Inspector pane to customize each user interface item

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:

  1. Make sure your MyFirstProgram project is loaded into Xcode.
  2. Choose View image Navigators image Show Project Navigator or press Command+1 to view the list of all the files that make up your MyFirstProgram project.
  3. Click the MainMenu.xib file. Xcode displays the user interface. Notice that the actual window of your MyFirstProgram is not visible until you click the MyFirstProgram icon.
  4. Click the MyFirstProgram icon that appears in the pane between the Project Navigator and the user interface. This displays the window of the MyFirstProgram user interface as shown in Figure 3-5.

    9781484212349_Fig03-05.jpg

    Figure 3-5. The MyFirstProgram icon displays the MyFirstProgram user interface

  5. Choose View image Utilities image Show Object Library. The Object Library appears in the bottom right corner of the Xcode window.
  6. Drag a Push Button from the Object Library and drop it near the bottom of your MyFirstProgram window. Notice that when you place the button in the middle and near the bottom of the window, blue guidelines appear to help you align user interface items as shown in Figure 3-6.

    9781484212349_Fig03-06.jpg

    Figure 3-6. Using blue guidelines to place a Push Button near the bottom of the MyFirstProgram window

  7. Click in the Search field at the Object Library and type label. Notice that the Object Library now only displays label user interface items as shown in Figure 3-7.

    9781484212349_Fig03-07.jpg

    Figure 3-7. Typing in the search field helps you easily find items in the Object Library

  8. Drag and drop the label from the Object Library to the middle of your MyFirstProgram window.
  9. Click the clear icon (the X in the gray circle) that appears in the right of the Search field at the bottom of the Object Library. The Object Library now displays all possible user interface items.
  10. Scroll through the Object Library until you find the Text Field item.
  11. Drag and drop the text field above the label so your entire user interface appears as shown in Figure 3-8. (Don’t worry about the exact position of each user interface item.)

    9781484212349_Fig03-08.jpg

    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.

  1. Click on the push button near the bottom of the MyFirstProgram window to select it.
  2. Choose View image Utilities image Show Attributes Inspector. The Attributes Inspector pane appears in the upper right corner of the Xcode window as shown in Figure 3-9.

    9781484212349_Fig03-09.jpg

    Figure 3-9. The Attributes Inspector pane lets you customize the appearance of items

  3. Click in the Title text field that currently displays “Button.” Delete any existing text in the Title text field, type Change Case, and press Return. The text on the push button now displays “Change Case.” However, the button width is too narrow.
  4. Choose View image Utilities image Show Size Inspector. The Size Inspector pane appears in the upper right corner of the Xcode window.
  5. Click in the Width text field, change the value to 120 as shown in Figure 3-10, and press Return. Xcode changes the width of the push button.

    9781484212349_Fig03-10.jpg

    Figure 3-10. The Width text field appears in the Size Inspector pane

  6. Click on the label to select it. To modify the size of the label, we’ll need to open the Size Inspector pane, which we can do by choosing View image Utilities image Show Size Inspector, but there’s a faster method using either keystroke shortcuts or icons.
  7. Press Option+Command+5 or just click the Size Inspector icon (it looks like a vertical ruler). The Size Inspector pane appears in the upper right corner of the Xcode window.
  8. Click in the Width text field, type 250, and press Return. Xcode widens the width of your label.
  9. Click on the text field to select it.
  10. Press Option+Command+5 or just click the Size Inspector icon (it looks like a vertical ruler). The Size Inspector pane appears in the upper right corner of the Xcode window.
  11. Click in the Width text field, type 250 and press Return. Xcode widens the width of your text field. At this point, all the user interface items appear off center.
  12. Drag each item until you see a blue guideline showing that you’ve centered it in the MyFirstProgram window as shown in Figure 3-11.

    9781484212349_Fig03-11.jpg

    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:

  • Write Swift code
  • Connect your user interface to your Swift code

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:

  1. Make sure the MainMenu.xib file is selected to display the MyFirstProgram user interface window on the screen. (If not, click the MainMenu.xib file in the Project Navigator and then click the MyFirstProgram icon to display the user interface window.)
  2. Choose View image Assistant Editor image Show Assistant Editor. The Assistant Editor displays the Swift code in the AppDelegate.swift file next to the user interface in the MainMenu.xib file as shown in Figure 3-12.

    9781484212349_Fig03-12.jpg

    Figure 3-12. The Assistant Editor lets you view the user interface and Swift code file side by side

  3. Click on the label on your MyFirstProgram window.
  4. Hold down the Control key and drag the mouse from the label underneath the @IBOutlet line in the AppDelegate.swift file until you see a horizontal line appear in the Swift code file as shown in Figure 3-13.

    9781484212349_Fig03-13.jpg

    Figure 3-13. Control-dragging creates a connection between a user interface item and your Swift code

  5. Release the Control key and the mouse. A pop-up window appears as shown in Figure 3-14.

    9781484212349_Fig03-14.jpg

    Figure 3-14. A pop-up window lets you define a name for your IBOutlet

  6. Click in the Name text field, type labelText, and click the Connect button. (The name you choose should be descriptive but can be anything you want.) Xcode creates an IBOutlet in your Swift file that looks like this:
    @IBOutlet weak var labelText: NSTextField!
  7. Click on the text field to select it.
  8. Hold down the Control key and drag the mouse from the text field to underneath the IBOutlet you just created until a horizontal line appears in the AppDelegate.swift file.
  9. Release the Control key and the mouse. A pop-up window appears.
  10. Click in the Name text field, type messageText, and click the Connect button. Xcode creates a second IBOutlet in your Swift file that looks like this:
    @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:

  • Create an IBAction method
  • Retrieve text from the text field
  • Capitalize all the text retrieved from the text field
  • Store the capitalized text in the label

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.

9781484212349_Fig03-15.jpg

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.

9781484212349_Fig03-16.jpg

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.

  1. Make sure the Assistant Editor is still open and displays the user interface and AppDelegate.swift file side by side.
  2. Click on the Change Case button on your MyFirstProgram user interface to select it.
  3. Hold down the Control key and drag the mouse underneath the last IBOutlet until a horizontal line appears as shown in Figure 3-17.

    9781484212349_Fig03-17.jpg

    Figure 3-17. Control-dragging from the button to the AppDelegate.swift file

  4. Release the Control key and the mouse. A pop-up window appears.
  5. Click in the Connection pop-up menu and choose Action as shown in Figure 3-18.

    9781484212349_Fig03-18.jpg

    Figure 3-18. Creating an Action connection

  6. Click in the Name text field and type changeCase. (The name you choose should be descriptive but can be anything you want.)
  7. Click in the Type pop-up menu and choose NSButton as shown in Figure 3-19. Then click the Connect button. Xcode creates an IBAction method that looks like this:
    @IBAction func changeCase(sender: NSButton) {
    }

    9781484212349_Fig03-19.jpg

    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.

  1. Make sure Xcode still displays your user interface and AppDelegate.swift file side by side.
  2. Choose View image Standard Editor image Show Standard Editor. Xcode now only shows your MyFirstProgram user interface.
  3. Click the AppDelegate.swift file in the Project Navigator. Xcode displays all the Swift code stored in the AppDelegate.swift file.
  4. Edit the IBAction changeCase method as follows:
    @IBAction func changeCase(sender: NSButton) {
        labelText.stringValue = messageText.stringValue.uppercaseString
    }
  5. Choose Product image Run. Your MyFirstProgram runs.
  6. Click in the text field of your MyFirstProgram user interface and type hello, world.
  7. Click the Change Case button. The label displays HELLO, WORLD as shown in Figure 3-20.

    9781484212349_Fig03-20.jpg

    Figure 3-20. Running the MyFirstProgram

  8. Choose MyFirstProgram image Quit MyFirstProgram. Xcode appears again.

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:

  • Choose Editor image Show/Hide Document Outline
  • Click the Document Outline icon

9781484212349_Fig03-21.jpg

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.

9781484212349_Fig03-22.jpg

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:

  • Choose View image Utilities image Show Connections Inspector
  • Press Option+Command+6
  • Click the Show Connections Inspector icon

9781484212349_Fig03-23.jpg

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.

9781484212349_Fig03-24.jpg

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:

  • Pick a project template to use (typically Cocoa Application)
  • Design and customize the user interface
  • Connect the user interface items to IBOutlets and IBAction methods
  • Write Swift code to make IBAction methods do something
  • Run and test your program

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset