Chapter    14

Working with Views and Storyboards

The most common part of every program’s user interface is a window that displays items such as buttons and text fields. In Xcode, windows are called views. In all but the simplest programs, a user interface will likely consist of two or more windows or views. That means your program needs to know how to open additional windows and close them again.

The two ways to create and store views are .xib files and .storyboard files. An .xib file holds one view so if you need to display multiple views, you’ll need to create multiple .xib files. A .storyboard file can hold one or more views.

You can create user interfaces with either .xib or .storyboard files, or a combination of both. Generally, .storyboard files are best for windows that logically link together. The biggest advantage of .storyboard files is that they link multiple views together in a logical sequence. The biggest disadvantage of .storyboard files is that if you have multiple views in your program, there may not be a logical sequence between displaying different views in a particular order. In that case, a .storyboard file can appear cluttered and be difficult to organize.

Whether you use .xib or .storyboard files is less important than knowing how to design a good user interface that makes performing tasks as easy as possible for the user.

Creating User Interface Files

When you create a project, Xcode gives you a choice between using storyboards or not as shown in Figure 14-1. If you choose not to use storyboards, then Xcode will create and store your user

interface in an .xib file. If you choose to use storyboards, then Xcode will store your user interface in a .storyboard file.

9781484212349_Fig14-01.jpg

Figure 14-1. When creating an OS X project, Xcode gives you a choice of choosing storyboards or not

After you’ve created a project, you can always add additional .xib or .storyboard files no matter if you initially started with storyboards or not.

Adding an .xib or .storyboard File

To add an .xib or .storyboard file to a project, follow these steps:

  1. From within Xcode choose File image New image File.
  2. Click User Interface under the OS X category.
  3. Click on Window (.xib) or Storyboard (.storyboard) as shown in Figure 14-2.

    9781484212349_Fig14-02.jpg

    Figure 14-2. Adding an .xib or .storyboard file to a project

  4. Click the Next button. Xcode asks where you want to store the project.
  5. Choose a folder to store your project and click the Create button. Your .xib or .storyboard user interface file appears in the Project Navigator pane.

If you create an .xib file using the above steps, you may still need to create a Swift file called a view controller to manage the view. To create a view controller Swift file and an .xib file at the same time, follow these steps:

  1. From within Xcode choose File image New image File.
  2. Click Source under the OS X category and click Cocoa Class as shown in Figure 14-3.

    9781484212349_Fig14-03.jpg

    Figure 14-3. Choosing Cocoa Class under the Source category

  3. Click the Next button. Xcode now asks for a class name, subclass, and whether you want to create an accompanying .xib file.
  4. Type any name in the Name text field.
  5. Click in the Subclass of: pop-up menu and choose NSViewController.
  6. Select the “Also create XIB file for user interface” check box and make sure the Language pop-up menu displays Swift as shown in Figure 14-4.

    9781484212349_Fig14-04.jpg

    Figure 14-4. Defining a class name, subclass, and .xib file

  7. Click the Next button. Xcode asks where you want to store your new file.
  8. Click the Create button. Xcode creates an .xib and accompanying .swift file in the Project Navigator pane.

Defining the Main User Interface

If your project only consists of a single .xib or .storyboard file, Xcode uses that one file as your program’s main user interface. However, if you have multiple user interface files (such as two .xib or .storyboard files, or a combination of both .xib and .storyboard files), you need to define which file should be your main user interface.

To define a main user interface file, follow these steps:

  1. Click on the project name in the top of the Project Navigator pane. Xcode displays a list of settings you can define for your project.
  2. Click the Main Interface pop-up menu and choose the user interface file (.xib or .storyboard) that you want to use as shown in Figure 14-5.

    9781484212349_Fig14-05.jpg

    Figure 14-5. Choosing the main user interface for your project

  3. Click on the .xib or .storyboard file in the Project Navigator pane that you chose in step 2 so you can edit your main user interface.

Displaying Multiple .xib Files

If you have multiple .xib files in a project, you need to designate one .xib file as your main user interface. That means the other .xib files won’t be visible until you specifically make them appear. To open one .xib file from another one, there are three steps you need to take:

  • Create a view controller and .xib file
  • Create an object to represent your view controller
  • Use the showWindow and close commands to open the .xib file and close it afterwards

To see how to open and close an .xib file, follow these steps:

  1. From within Xcode choose File image New image Project.
  2. Click Application under the OS X category.
  3. Click Cocoa Application and click the Next button. Xcode now asks for a product name.
  4. Click in the Product Name text field and type XIBProgram.
  5. Make sure the Language pop-up menu displays Swift and that no check boxes are selected.
  6. Click the Next button. Xcode asks where you want to store the project.
  7. Choose a folder to store your project and click the Create button.
  8. Click the MainMenu.xib file in the Project Navigator. Your program’s user interface appears.
  9. Click the XIBProgram icon to display the window of your program’s user interface.
  10. Choose View image Utilities image Show Attributes Inspector. The Attributes Inspector pane appears as shown in Figure 14-6. The Attributes Inspector gives you options for modifying the appearance of each window of your user interface. For now, don’t change anything.

    9781484212349_Fig14-06.jpg

    Figure 14-6. The Attributes Inspector pane lets you modify the appearance of a window

  11. Choose View image Utilities image Show Object Library. The Object Library appears in the bottom right corner of the Xcode window.
  12. Drag a Push Button on the window of your user interface and change its label to read “Open Window.”

At this point, your program consists of a MainMenu.xib file that displays a single window with a push button on it. Now we need to create a view controller (containing Swift code) and an accompanying .xib file by following these steps:

  1. Choose File image New image File. A template dialog appears.
  2. Choose Source under the OS X category and click Cocoa Class (see Figure 14-3). Click the Next button. Another dialog appears, asking for a class name.
  3. Type secondView in the Class Name text field.
  4. Click in the Subclass of: pop-up menu and choose NSWindowController.
  5. Select the “Also create XIB file for user interface” check box.
  6. Make sure the Language pop-up menu displays Swift as shown in Figure 14-7.

    9781484212349_Fig14-07.jpg

    Figure 14-7. Defining the features of a second. xib file and its view controller

  7. Click the Next button. Xcode asks where you want to store your file.
  8. Click the Create button. Xcode displays a secondView.swift and a secondView.xib file in the Project Navigator pane.

At this point, you’ve created a second. xib file and an accompanying view controller file. Now it’s time to write Swift code to make everything work by following these steps:

  1. Click in the MainMenu.xib file in the Project Navigator pane.
  2. Choose View image Assistant Editor image Show Assistant Editor. Xcode shows the AppDelegate.swift file to the right of the MainMenu.xib file.
  3. Move the mouse pointer over the Open Window button, hold down the Control key and drag the mouse above the last curly bracket in the AppDelegate.swift file.
  4. Release the Control key and the mouse button. A pop-up window appears.
  5. Click the Connection pop-up menu and choose Action.
  6. Click in the Name text field and type openWindow.
  7. Click in the Type pop-up menu and choose NSButton as shown in Figure 14-8.

    9781484212349_Fig14-08.jpg

    Figure 14-8. Creating an IBAction method for the Open Window button

  8. Click the Connect button. Xcode creates an empty IBAction method.
  9. Underneath the @IBOutlet line, type the following:
    var windowController = secondView(windowNibName: "secondView")
  10. Modify the IBAction method as follows:
    @IBAction func openWindow(sender: NSButton) {
        windowController.showWindow(sender)
    }
  11. Click on the secondView.xib file. The Assistant Editor should stay open and show the secondView.swift file to the right.
  12. Drag a Push Button on to the window of the secondView.xib file and label this button Back.
  13. Move the mouse button over this Back button you just created, hold down the Control key, and drag the mouse above the last curly bracket in the secondView.swift file.
  14. Release the Control key and the mouse. A pop-up window appears.
  15. Click the Connection pop-up menu and choose Action.
  16. Click in the Name text field and type closeWindow.
  17. Click in the Type pop-up menu and choose NSButton.
  18. Click the Connect button.
  19. Modify the IBAction method closeWindow as follows:
    @IBAction func closeWindow(sender: NSButton) {
        self.close()
    }
  20. Choose Product image Run. Your program appears.
  21. Click the Open Window button. The second window appears as shown in Figure 14-9.

    9781484212349_Fig14-09.jpg

    Figure 14-9. Running the XIBProgram

  22. Click the Back button to close the second window defined by your secondView.xib file.
  23. Choose XIBProgram image Quit XIBProgram.

What you did was create a second .xib file with a view controller. Then you created an object in the AppDelegate.swift file called windowController, based on the secondView class that loads the secondView.xib file.

Inside the openWindow IBAction method, you used the showWindow method to open the .xib file stored in the windowController object, which is the secondView class.

When this second window appears, you clicked on the Back button, which ran the self.close() command that closed the window.

As you can see, opening and closing multiple .xib files requires Swift code. To make transitioning from one window to another easier, Xcode also offers storyboards.

Using Storyboards

Storyboards consist of two partsStoryboard:

  • Scenes – Display the windows of your user interface
  • Segues – Define the transitions between scenes

You create scenes and place items on scenes such as buttons and text fields. Then you connect scenes using segues. By doing this, you can define how your user interface displays information on the screen.

To experiment with storyboards, you’ll need to create a project that uses storyboards by following these steps:

  1. From within Xcode choose File image New image Project.
  2. Click Application under the OS X category.
  3. Click Cocoa Application and click the Next button. Xcode now asks for a product name.
  4. Click in the Product Name text field and type StoryProgram.
  5. Make sure the Language pop-up menu displays Swift and that only the “Use Storyboards” check box is selected.
  6. Click the Next button. Xcode asks where you want to store the project.
  7. Choose a folder to store your project and click the Create button.

When you create a project that uses storyboards, you’ll see two boxes where one box represents your window or view (labeled Window Controller) and the second box represents that window’s contents (labeled View Controller in its title bar) as shown in Figure 14-10 . The second box (that has an arrow pointing to it) is where you can place additional user interface items such as buttons, text fields, and labels.

9781484212349_Fig14-10.jpg

Figure 14-10. A view controller and view in a storyboard

You place items from the Object Library onto the bottom window (labeled View Controller). To add additional windows to a storyboard, you use the Object Library and drag different controller objects into your storyboard as shown in Figure 14-11.

9781484212349_Fig14-11.jpg

Figure 14-11. Controllers you can add to a storyboard

Zooming In and Out of a Storyboard

When you click on a .storyboard file in the Project Navigator pane, Xcode displays your storyboard. The problem with storyboards is that they tend to consist of multiple scenes and segues, which you can’t easily see.

To help you see your entire storyboard or just a part of it, you can zoom magnification in and out. Xcode offers two ways to zoom in and out:

  • Double-click on the blank space away from anything on the storyboard (this toggles the storyboard between zooming in and zooming out).
  • Right-click on the blank space on the storyboard and choose a magnification level from a pop-up menu as shown in Figure 14-12.

9781484212349_Fig14-12.jpg

Figure 14-12. Right-clicking displays a magnification pop-up menu

The lower to zoom magnification, the more of the storyboard you’ll be able to see, so a zoom magnification of 25% displays more of the storyboard than a zoom magnification of 50%.

 Note  You’ll need to change the storyboard magnification to 100% when you want to place different items on the user interface such as buttons or text fields.

Adding Scenes to a Storyboard

You can add scenes to a storyboard at any magnification. Lower magnifications (such as 25% or 50%) just make it easier to see how the individual scenes in your storyboard are connected. To place a new scene on a storyboard, follow these steps:

  1. Click on the .storyboard file in the Project Navigator pane.
  2. Choose View image Utilities image Show Object Library.
  3. Drag any blue controller from the Object Library (see Figure 14-11) anywhere on the storyboard.

The five types of controllers you can place on a storyboard include:

  • View Controller – Controls an .xib file so you can include it with a storyboard
  • Window Controller – Controls a single window or view
  • Page Controller – Defines the animation between views
  • Vertical/Horizontal Split View Controller – Displays two views side by side or stacked on top of each other
  • Tab View Controller – Displays a tabbed interface that controls two or more views

You can think of a Window Controller as a window that contains a view. The view displayed inside the window is identified by an arrow pointing from the Window Controller to the view as shown in Figure 14-13.

9781484212349_Fig14-13.jpg

Figure 14-13. A Window Controller contains a single view

On the other hand, a Vertical/Horizontal Split View Controller acts like a window that holds two views either side by side or stacked on top of each other as shown in Figure 14-14.

9781484212349_Fig14-14.jpg

Figure 14-14. A Split View Controller contains two views

The Tab View Controller also consists of a single window that can contain two or more views. The difference is that it can display tabs where each tab represents a different view as shown in Figure 14-15. You can also add more than two views to a Tab View Controller.

9781484212349_Fig14-15.jpg

Figure 14-15. A Tab View Controller displays two or more views in one window identified by tabs

Defining the Initial Scene in a Storyboard

In every storyboard, one scene must be designated as the initial scene, which is the first window or view that appears when your program runs. Xcode identifies the initial scene with an arrow pointing to the right.

Another way to identify the initial scene is to click on the blue icon in the top middle part of the controller and open the Show Attributes Inspector pane. If the “Is Initial Controller” check box is selected, then the currently selected window is the initial scene as shown in Figure 14-16.

9781484212349_Fig14-16.jpg

Figure 14-16. An arrow and the “Is Initial Controller” check box identifies the initial scene

To change the initial scene, you can do one of the following:

  • Drag the initial scene arrow and make it point to a different scene
  • Select the “Is Initial Controller” check box for a different scene

Note: There can only be one initial scene at a time.

Connecting Scenes with Segues

When a storyboard consists or two or more scenes, you need a way to display those other scenes. First, you need a way to switch from one scene to another. Second, you need a way to go back. Third, you may need to pass data from one scene to another.

Moving from one scene to another involves creating a segue between scenes. To create a segue between scenes, follow these steps:

  1. Make sure your StoryProgram project is loaded in Xcode and click on the Main.storyboard file in the Project Navigator pane.
  2. Place a button on the first scene.
  3. Move the mouse pointer over this button, hold down the Control key, and drag the mouse from this button over the second scene. Xcode highlights the second scene as shown in Figure 14-17.

    9781484212349_Fig14-17.jpg

    Figure 14-17. Control-dragging the mouse from a button to another scene creates a segue

  4. Release the Control key and the mouse. Xcode displays a pop-up menu as shown in Figure 14-18.

    9781484212349_Fig14-18.jpg

    Figure 14-18. A pop-up menu lets you define how to display the scene

  5. Choose an option such as popover or sheet. Xcode creates a segue between the two scenes. If you click on a segue, Xcode highlights the button that runs the segue. If you open the Show Attributes Inspector pane, you can give the segue an identifying name and also change the segue style as shown in Figure 14-19.

    9781484212349_Fig14-19.jpg

    Figure 14-19. Clicking on a segue lets you edit its attributes and identify the user interface item that runs that segue

Displaying Scenes From a Segue

A segue not only connects one scene to another scene, but also defines how that second scene appears. The five different ways a scene can appear include:

  • Popover – Displays a scene as a window that pops up over or under the button connected to the segue
  • Show – Displays a scene as a separate window that can be moved and resized
  • Custom – Lets you create a custom appearance for the scene
  • Modal – Displays a scene as a dialog that won’t let the user do anything else until dismissing this scene
  • Sheet – Displays a scene that slides down from the title bar of the window

When you first create a segue, you can define how the segue should display the scene. However, you can always change this by following these steps:

  1. Make sure your StoryProgram project is loaded in Xcode and click on the Main.storyboard file in the Project Navigator pane.
  2. Click on the segue that you want to modify. Xcode highlights your chosen segue.
  3. Choose View image Utilities image Show Attributes Inspector. The Attributes Inspector pane lets you modify the Identifier and Style properties (see Figure 14-19).
  4. Click in the Style pop-up menu in the Show Attributes Inspector pane and choose a different style such as Modal or Sheet.

Removing a Scene After a Segue

A segue works in one direction from one scene to a second scene. When you create a second scene using the Modal, Sheet, Popover, or Custom segue, you can close this second scene using Swift code. To do this, you need to create a Swift controller file for your scene. Then connect a user interface item from that scene (such as a button) to define an IBAction method where you can use Swift code to close a scene.

If you open a scene using a Show segue, then the user can close the scene by clicking the close button, which doesn’t require you to write any Swift code at all.

To remove a scene after a Modal, Sheet, Popover, or Custom segue, follow these steps:

  1. Make sure your StoryProgram project is loaded in Xcode and click on the Main.storyboard file in the Project Navigator pane.
  2. Place a button on the first scene and change the button’s label to Open Scene.
  3. Click on the segue, choose View image Utilities image Show Attributes Inspector, and make sure the Style pop-up menu displays Modal, Sheet, Popover, or Custom.
  4. Choose File image New image File. Xcode displays different templates you can use.
  5. Choose Source under OS X and click the Cocoa Class icon. Then click the Next button. Another dialog appears, asking for a name and a subclass.
  6. Click in the Name text field and type a descriptive name for your class to control your scene.
  7. Click in the Subclass of: pop-up menu and choose NSViewController.
  8. Clear the “Also create XIB file for user interface” check box.
  9. Make sure the Language pop-up menu displays Swift as shown in Figure 14-20. Click the Next button. Xcode asks where you want to save your new Swift class.

    9781484212349_Fig14-20.jpg

    Figure 14-20. Creating a Swift class to control a scene in a storyboard

  10. Choose a folder and click the Create button. Xcode displays your Swift class in the Project Navigator pane. At this point, the Swift class and the scene aren’t connected so we have to fix this by making the scene’s view controller a class of the Swift file we just created.
  11. Click on the Main.storyboard file to display your user interface.
  12. Click on the blue View Controller icon on the scene that has a segue pointing to it. This should be the scene that you want to go away.
  13. Choose View image Utilities image Show Identity Inspector.
  14. Click in the Class pop-up menu and choose secondView, the view controller you created earlier as shown in Figure 14-21.

    9781484212349_Fig14-21.jpg

    Figure 14-21. Connecting a scene to a Swift view controller file

  15. Drag a push button on to this second scene and change its label to Close Scene.
  16. Choose View image Assistant Editor image Show Assistant Editor. The Assistant Editor displays the secondView Swift file you just created.
  17. Move the mouse pointer over the push button on this second scene, hold down the Control key, and drag the mouse just above the last curly bracket in the bottom of the secondView.swift file. A pop-up window appears.
  18. Click in the Connection pop-up menu and choose Action.
  19. Click in the Name text field and type closeScene.
  20. Click in the Type pop-up menu and choose NSButton. Then click the Connect button. Xcode displays an empty IBAction method.
  21. Modify the IBAction method as follows:
    @IBAction func closeScene(sender: NSButton) {
        self.dismissController(self)

    }
  22. Choose Product image Run. Your program’s initial scene appears with the button Open Scene.
  23. Click the Open Scene. Your second scene appears in the way you defined the segue such as Modal, Sheet, Popover, or Custom.
  24. Click the Close Scene button on this second scene. The second scene goes away.
  25. Choose StoryProgram image Quit StoryProgram.

Passing Data Between Scenes

When you make changes on one scene and then open another scene, you may want that second scene to know of any changes you made earlier on the previous scene. To do this, you need to do the following:

  • In the first scene, create a prepareForSegue method that uses the segue.destinationViewController command to identify the name of the second scene’s view controller and assign a value to the representedObject property.
  • In the second scene’s view controller, declare a variable to hold the data you want to receive from the first scene and unwrap the value from representedObject.

To see how to pass data from one scene to another, follow these steps:

  1. Make sure your StoryProgram project is loaded in Xcode and click on the Main.storyboard file in the Project Navigator pane.
  2. Drag a text field and widen it on the scene that contains the Open Scene button as shown in Figure 14-22.

    9781484212349_Fig14-22.jpg

    Figure 14-22. The user interface of the initial scene

  3. Choose View image Assistant Editor image Show Assistant Editor to display the ViewController.swift file that controls the initial scene.
  4. Move the mouse pointer over the text field, hold down the Control key, and drag the mouse from the text field to under the class ViewController line.
  5. Release the Control key and mouse. A pop-up menu appears.
  6. Click in the Name text field, type passedText, and click the Connect button. Xcode creates an IBOutlet like this:
    @IBOutlet weak var passedText: NSTextField!
  7. Write a prepareForSegue method so the entire code in the ViewController.swift file looks like this:
    import Cocoa

    class ViewController: NSViewController {

        @IBOutlet weak var passedText: NSTextField!

        override func viewDidLoad() {
            super.viewDidLoad()

            // Do any additional setup after loading the view.
        }

        override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
            let secondScene = segue.destinationController as! secondView
            secondScene.representedObject = passedText.stringValue
        }

        override var representedObject: AnyObject? {
            didSet {
            // Update the view, if already loaded.
            }
        }

    }

    The passedText IBOutlet retrieves the text that the user types into the text field. Then the prepareForSegue method creates a constant called “secondScene” that represents the segue’s destination, which is the secondView class. Then it takes the text from the passedText IBOutlet and stores it into the representedObject property.

  8. Click on the second scene in your storyboard, place a Label on there and make it wider as shown in Figure 14-23.

    9781484212349_Fig14-23.jpg

    Figure 14-23. The user interface of the second scene

  9. Choose View image Assistant Editor image Show Assistant Editor. If the assistant editor does not display the secondView.swift file, click Automatic in the upper left corner of the assistant editor to display a menu. From this menu, choose Manual image StoryProgram image StoryProgram and then click on the secondView.swift file.
  10. Move the mouse pointer over the label, hold down the Control key, and drag the mouse from the label to under the class secondView line.
  11. Release the Control key and mouse. A pop-up menu appears.
  12. Click in the Name text field, type receivedText, and click the Connect button. Xcode creates an IBOutlet like this:
    @IBOutlet weak var receivedText: NSTextField!
  13. Modify the viewDidLoad method so the entire code in the secondView.swift file looks like this:
    import Cocoa

    class secondView: NSViewController {

        @IBOutlet weak var receivedText: NSTextField!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do view setup here.
                      receivedText.stringValue = self.representedObject! as! String
        }

        @IBAction func closeScene(sender: NSButton) {
            self.dismissController(self)
        }

    }

    The receivedText IBOutlet displays the text that appears in the label. Then the viewDidLoad method takes the representedObject property, casts or turns it into a String data type, and stores this into the receivedText IBOutlet.

  14. Click on the segue and choose View image Utilities image Show Attributes Inspector to display the Attributes Inspector pane.
  15. Choose Product image Run. Your initial scene appears.
  16. Click in the text field and type any text such as your name.
  17. Click the Open Scene button. Your second scene appears with the text you typed now displayed in the label.
  18. Click the Close Scene button to make the second scene go away.
  19. Choose StoryProgram image Quit StoryProgram.

Summary

You create your user interface and store them in multiple .xib files or a single .storyboard file that contains multiple scenes. To open and close different .xib files, you have to write Swift code. To open a scene in a storyboard, you just need to Control-drag from a button on one scene to another scene.

To make a second scene close after opening it, you have to write Swift code. You also need to use Swift code to transfer data from one scene to another. When you transfer data from one scene to another, you use the representedObject property. To access any value in the representedObject property, you must unwrap it and cast or turn it into a specific data type.

Storyboards let you define the order that scenes appear that make up your program’s user interface. To make it easy to see your entire storyboard, you can adjust the magnification to shrink or enlarge the storyboard. However when you want to place items on a storyboard scene, you must enlarge the magnification to 100%.

When you add additional scenes in a storyboard, you’ll need to create Swift files that control those scenes. These Swift files need to be of the NSViewController class, and then you must connect your scene to that Swift file.

Designing your program’s user interface involves using .xib or .storyboard files, or a combination of both. Storyboards reduce the need to write Swift code, but with both types of files, you’ll still need to write Swift code to make your user interface work completely.

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

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