iPhone Application Development : Using Switches, Segmented Controls, and Web Views (part 1)

2/4/2011 4:37:18 PM
As you’ve probably noticed by now, we prefer to work on examples that do something. It’s one thing to show a few lines of code in a chapter and say “this will do <blah>,” but it’s another to take a collection of features and combine them in a way that results in a working application. In some cases, the former approach is unavoidable, but this isn’t one of them. Our first hands-on example makes use of web views, a segmented control, and a toggle switch.

Implementation Overview

In this project, we create an application that displays flower photographs and flower information from the website The application will enable a user to touch a flower color within a segmented control (UISegmentedControl), resulting in a flower of that color being fetched and displayed from the FloraPhotographs site in a web view (UIWebView). The user can then use a toggle switch (UISwitch) to show and hide a second web view that contains details about the flower being displayed. Finally, a standard button (UIButton) will enable the user to fetch another flower photo of the currently selected color from the site. The result should look very much like Figure 1.

Figure 1. The finished application will make use of a segmented control, a switch, and two web views.

Setting Up the Project

This project will, once again, use the View-Based Application template we’re starting to love. If it isn’t already running, launch Xcode (Developer/Applications), and then create a new project called FlowerWeb.

You should now be accustomed to what happens next. Xcode sets up the project and creates the default view in FlowerWebViewController.xib and a view controller class in FlowerWebViewController. We’ll start with setting up the outlets and actions we need in the view controller.

Preparing the Outlets and Actions

To create the web-based image viewer, we need three outlets and two actions. The segmented control will be connecting to an outlet called colorChoice because we’ll be using it to choose which color is displayed. The web view that contains the flower will be connected to flowerView, and the associated details web view to flowerDetailView.

For the actions, the application must do two things: get and display a flower image, which we’ll define as the action method getFlower; and toggle the flower details on and off, something we’ll handle with a toggleFlowerDetail action.

Why Don’t We Need an Outlet for the Switch?

We don’t need to include an outlet for the switch because we will be connecting its Value Changed event to the toggleFlowerDetail method. When the method is called, the sender parameter sent to the method will reference the switch, so we can just use sender to determine whether the switch is on or off.

If we have more than one control using toggleFlowerDetail, it would be helpful to define outlets to differentiate between them, but in this case, sender will suffice.

Open the flowerWebViewController.h file in Xcode and create the IBOutlets for colorChoice, flowerView, and flowerDetailView. Then add the IBActions for getFlower and toggleFlowerDetail. Finally, add @property directives for the segmented control and both web views so that we can easily manipulate them in our code.

The completed header file should look very similar to Listing 1.

Listing 1.
#import <UIKit/UIKit.h>

@interface FlowerWebViewController : UIViewController {
IBOutlet UISegmentedControl *colorChoice;
IBOutlet UIWebView *flowerView;
IBOutlet UIWebView *flowerDetailView;


@property (nonatomic, retain) UISegmentedControl *colorChoice;
@property (nonatomic, retain) UIWebView *flowerView;
@property (nonatomic, retain) UIWebView *flowerDetailView;


Save the header file and open the view controller implementation file (flowerWebViewController.m). Add matching @synthesize directives for each of the properties you declared in the header. These, as always, should be added after the @implementation directive:

@synthesize colorChoice;
@synthesize flowerDetailView;
@synthesize flowerView;

Now, let’s build the user interface. Open the FlowerWebViewController.xib file in Interface Builder, and make sure that the view is open and visible. We’ll begin by adding the segmented control.

Adding a Segmented Control

Add a segmented control to the user interface by opening the Library (Tools, Library), finding the Segmented Control (UISegmentedControl) object, and dragging it into the view. Position the control near the top of the view in the center. Because this control will ultimately be used to choose colors, click and drag a label (UILabel) into the view as well, position it above the segmented control, and change it to read Choose a Flower Color:. Your view should now resemble Figure 2.

Figure 2. The default segmented control has two buttons, First and Second.

By default, the segmented control will have two segments, titled First and Second. You can double-click these titles and edit them directly in the view, but that won’t quite get us what we need.

For this project, we need a control that has four segments, each labeled with a color: Red, Blue, Yellow, and Green. These are the colors that we can request from the FloraPhotographs website for displaying. Obviously, we need to add a few more segments to the control before all the choices can be represented.

Adding and Configuring Segments

The number of segments displayed in the segmented control is configurable in the Attributes Inspector for the object. Select the control that you’ve added to the view, and then press Command+1 to open the Attributes Inspector, demonstrated in Figure 3.

Figure 3. Use the Attributes Inspector for the segmented control to increase the number of segments displayed.

Using the Segments field, increase the number from 2 to 4. You should immediately see the new segments displayed. Notice that directly below where you set the number of segments in the inspector is a drop-down with entries for each segment you’ve added. You can choose a segment in this drop-down, and then specify its title in the Title field. You can even add images resources and have them displayed within each segment.

By the Way

Note that the first segment is segment 0, the next is segment 1, and so on. It’s important to keep this in mind when you’re checking to see which segment is selected. The first segment is not segment 1, as you might assume.

Update the four segments in the control so that the colors Red, Blue, Yellow, and Green are represented.

Sizing the Control

Chances are, the control you’ve set up doesn’t quite look right in the view. To size the control to aesthetically pleasing dimensions, use the selection handles on the sides of the control to stretch and shrink it appropriately. You can even optimize the size of individual segments using the Segmented Control Size options in the Size Inspector (Command+3), as shown in Figure 4.

Figure 4. You can use the Size Inspector to size each segment individually, if desired.

Choosing a Segment Control Appearance

In addition to the usual color options and controls available in Attributes Inspector, there are four variations of how the segmented control can be presented. Use the Style drop-down menu  to choose between Plain, Bordered, Bar, and Bezeled. Figure 5 shows each of these.

Figure 5. You can choose between four different presentation styles for your segmented control.

For this project, stick with Plain, Bordered, or Bezeled. The segmented control should now have titles for all the colors and a corresponding label to help the user understand its purpose.

To finish things up for the segmented control, we need to connect it to the outlet we defined earlier (colorChoice) and make sure that it triggers the getFlower action method when a user switches between colors.

Connecting to the Outlet

To connect the segmented control to the colorChoice outlet, make sure the Document window is visible, and then Control-drag from the File’s Owner icon to either the visual representation of the control in the view or to its icon in the Document window, and then release the mouse button. When prompted, choose the colorChoice outlet to finish the connection, as shown in Figure 6.

Figure 6. Connect the segmented control to the colorChoice outlet so that we can easily access the selected color from within our application.

Connecting to the Action

Like other UI elements, the segmented control can react to many different touch events. Most frequently, however, you’ll want to carry out an action when the user clicks a segment and switches to a new value (such as choosing a new color in this app). Thankfully, Apple has implemented a Value Changed event that does exactly what we want!

In our application, we want to load a new flower if the user switches colors. To do this, we need to create a connection from the Value Changed event to the getFlower action. Open the Connections Inspector by selecting the segmented control and then pressing Command+2. Drag from the circle beside Value Changed to the File’s Owner icon in the Document window, and release your mouse button. When prompted, choose the getFlower action method, as shown in Figure 7.

Figure 7. Connect from the Value Changed event to the getFlower action.

The segmented control is now wired into the interface and ready to go. Let’s add our other interface objects, and then write the code to pull it together.

  •  iPhone Application Development : Using Advanced Interface Objects and Views - User Input and Output
  •  Windows Phone 7 Development : Wiring Up Events to an Application Bar ( part 2)
  •  Windows Phone 7 Development : Wiring Up Events to an Application Bar ( part 1) - Reacting to Add Button Events
  •  Adding an Application Bar to a Windows Phone 7 Application (part 3) - Adding an Application Bar Using Managed Code
  •  Adding an Application Bar to a Windows Phone 7 Application (part 2) - Adding a Local Application Bar Using XAML & Adding Menu Items
  •  Adding an Application Bar to a Windows Phone 7 Application (part 1) - Adding Images for Use with Application Bar Buttons & Adding a Global Application Bar Using XAML
  •  iPhone Application Development : Creating and Managing Image Animations and Sliders (part 3) - Finishing the Interface
  •  iPhone Application Development : Creating and Managing Image Animations and Sliders (part 2) - Adding an Image View
  •  iPhone Application Development : Creating and Managing Image Animations and Sliders (part 1)
  •  iPhone Application Development : User Input and Output
  •  Windows Phone 7 : Using Accelerometer Data to Move a Ball
  •  Server-Side Browser Detection and Content Delivery : Mobile Detection (part 4) - Device Libraries
  •  Server-Side Browser Detection and Content Delivery : Mobile Detection (part 3) - Transcoders
  •  Server-Side Browser Detection and Content Delivery : Mobile Detection (part 2) - Detecting the Context
  •  Server-Side Browser Detection and Content Delivery : Mobile Detection (part 1) - HTTP
  •  Using Windows Phone 7 Technologies : Retrieving Accelerometer Data (part 2)
  •  Using Windows Phone 7 Technologies : Retrieving Accelerometer Data (part 1)
  •  Using Windows Phone 7 Technologies : Understanding Orientation and Movement
  •  Programming the Mobile Web : HTML 5 (part 4) - Client Storage
  •  Programming the Mobile Web : HTML 5 (part 3) - Offline Operation
    Top 10
    Programming Symmetrical Encryption (part 3) - Encrypting and Decrypting Data
    Microsoft XNA Game Studio 3.0 : Controlling Color (part 1) - Games and Classes & Classes as Offices
    iPhone 3D Programming : Drawing an FPS Counter (part 1) - Generating a Glyphs Texture with Python
    Programming with DirectX : Game Math - Matrices
    Building LOB Applications : Implementing CRUD Operations in WCF Data Services
    Microsoft XNA Game Studio 3.0 : Displaying Images - Using Resources in a Game (part 1) - Loading XNA Textures
    Windows 7 : Protecting Your Computer While Browsing (part 3)
    Windows Server 2008 : Installing and Upgrading IIS 7.5
    Windows 7 : Navigating the Computer Security Maze
    Restart Manager in Windows Vista
    Most View
    Algorithms for Compiler Design: PREDICTIVE PARSING ERROR RECOVERY
    ASP.NET 4 in VB 2010 : Membership - Role-Based Security
    Programming .NET Components : Visual Studio 2005 and Security
    Programmatic Security (part 4) - Permission Set Classes
    Collaborating Within an Exchange Server Environment Using Microsoft Office SharePoint Server 2007 : Understanding the History of SharePoint Technologies
    The SQL Server 2008 Configuration Manager
    iPhone 3D Programming : Textures and Image Capture - Dealing with Size Constraints
    Caching Page Content
    Windows 7 : Maintaining Your System Configuration (part 3) - Configuring User Profiles, Environment Variables, and Startup and Recovery
    Windows Server 2008: Active Directory Infrastructure - Detailing Real-World Replication Designs
    Creating Link-Worthy Content and Link Marketing : Types of Link Building (part 2)
    Windows Server 2008 : Installing and Configuring FTP Services (part 1) - Installing the FTP Server & Creating a Secure FTP 7.5 Site Using SSL
    Programming the Mobile Web : HTML 5 (part 2) - The canvas Element
    Sharepoint 2007: Edit the Properties of a File or a List Item
    Assembly vs. C
    Optimizing the Desktop Environment in Vista
    Working with the REST API
    The Hello-World Midlet
    SQL Server 2008 : Managing Query Performance - Forcing a Specific Execution Plan