MOBILE

iPhone Application Development : Working with Text, Keyboards, and Buttons (part 1) - Adding Text Fields

1/16/2011 3:37:45 PM
Launch Xcode (Developer/Applications), and then choose File, New Project.

Select the iOS Application project type, and then find and select the View-Based Application option in the Template list. Click Choose to continue, and then enter the project name, FieldButtonFun, and save the new project.

Xcode will set up a skeleton project for you. As before, we’ll be focusing on the view, which has been created in FieldButtonFunViewController.xib, and the view controller class FieldButtonFunViewController.

Preparing the Outlets and Actions

This project contains a total of six input areas: Three text fields will be used to collect the place, verb, and number values. We’ll be calling these thePlace, theVerb, and theNumber, respectively. The project also requires two text views: one to hold the editable story template, theTemplate; and the other to contain the output, theStory. Finally, a single button is used to trigger a method, createStory, which will create the story text.

By the Way

Yes, we’ll be using a text view for output as well as input. Text views provide a built-in scrolling behavior and can be set to read-only, making them convenient for both collecting and displaying information. They do not, however, allow for rich text input or output. A single font style is all you get!


Start by preparing the outlets and actions in the view controller’s header file, FieldButtonFunViewController.h. Edit the file to contain contain the code shown in listing 1.

Listing 1.
 1: #import <UIKit/UIKit.h>
2:
3: @interface FieldButtonFunViewController : UIViewController {
4: IBOutlet UITextField *thePlace;
5: IBOutlet UITextField *theVerb;
6: IBOutlet UITextField *theNumber;
7: IBOutlet UITextView *theStory;
8: IBOutlet UITextView *theTemplate;
9: IBOutlet UIButton *generateStory;
10: }
11:
12: @property (retain,nonatomic) UITextField *thePlace;
13: @property (retain,nonatomic) UITextField *theVerb;
14: @property (retain,nonatomic) UITextField *theNumber;
15: @property (retain,nonatomic) UITextView *theStory;
16: @property (retain,nonatomic) UITextView *theTemplate;
17: @property (retain,nonatomic) UIButton *generateStory;
18:
19: -(IBAction)createStory:(id)sender;
20:
21: @end

Lines 4–9 create the outlets for each of the input elements, while lines 12–17 establish them as properties so that we can easily manipulate their contents. Line 19 declares a createStory method where we’ll eventually implement the logic behind the application.

By the Way

If you’re paying close attention, you may notice that we’ve declared an outlet and a property for the view’s button, generateButton. As we mentioned earlier, typically buttons are used to trigger a method when a certain event takes place, so we don’t usually need an outlet or property to manipulate them.

In this example, however, we’re going to programmatically alter the visual appearance of the button, so we need to be able to access the object, not just receive messages from it.


After you’ve set up the outlets and actions, save the header file and open FieldButtonViewController.m. As you’ve learned, properties usually have corresponding @synthesize directives so that they can easily be accessed in code. Add the appropriate statements for all the properties defined in the header. Your additions should fall after the @implementation directive and look like this:

@synthesize thePlace;
@synthesize theVerb;
@synthesize theNumber;
@synthesize theStory;
@synthesize theTemplate;
@synthesize generateStory;

That should be all the setup we need for now. Let’s turn our attention to creating the user interface.

In the previous hour, you learned that the MainWindow.xib is loaded when the application launches and that it will instantiate the view controller, which subsequently loads its view from the second XIB file in the project (in this case, FieldButtonFunViewController.xib). Locate the file in the project’s Resources folder, and then double-click it to launch Interface Builder.

When Interface Builder has started, open the XIB file’s Document window (Window, Document), and then double-click the view icon to open the blank view for editing.

Adding Text Fields

Begin creating the user interface by adding three text fields to the top of the view. To add a field, open the Objects Library by choosing Tools, Library, and then locate the Text Field object (UITextField) and drag it into the view. Repeat this two more times for the other two fields.

Stack the fields on top of one another, leaving enough room so that the user can easily tap a field without hitting all of them. To help the user differentiate between the three fields, you’ll also want to add labels to the view. Click and drag the Label (UILabel) object from the Library into the view. Align three labels directly across from the three fields. Double-click the label within the view to set its text. I’ve labeled my fields Place, Verb, and Number, from top to bottom, as shown in Figure 1.

Figure 1, Add text fields and labels to differentiate between them.


Editing Text Field Attributes

The fields that you’ve created are technically fine as is, but you can adjust their appearance and behavior to create a better user experience. To view the field attributes, click a field, and then press Command+1 (Tools, Attributes Inspector) to open the Attributes Inspector (see Figure 2).

Figure 2. Editing a field’s attributes can help create a better UI.

For example, you can use the Placeholder Text field to enter text that will appear in the background of the field until the user begins editing. This can be a helpful tip or an additional explanation of what the user should be entering.

You may also choose to activate the Clear button. The Clear button is a small X icon added to a field that the user can touch to quickly erase the contents. To add the Clear button, simply choose one of the visibility options from the Clear button pop-up menu; the functionality is added for free to your application! Note that you may also choose to automatically clear the field when the user taps it to start editing. Just enable the Clear When Editing Begins check box.

Add these features to the three fields within the view. Figure 3 shows how they will appear in the application.

Figure 3. Placeholder text can provide helpful cues to the user, while the Clear button makes it simple to remove a value from a field.


Did you Know?

Placeholder text also helps identify which field is which within the Interface Builder Document window. It can make creating your connections much easier down the road!


In addition to these changes, attributes can adjust the text alignment, font and size, and other visual options. Part of the fun of working in Interface Builder is that you can explore the tools and make tweaks (and undo them) without having to edit your code.

Customizing the Keyboard Display with Text Input Traits

Probably the most important attributes that you can set for an input field are the “text input traits,” or, simply, how the keyboard is going to be shown onscreen. Seven different traits are currently available:

Capitalize: Controls whether the iPhone will automatically capitalize words, sentences, or all the characters entered into a field.

Correction: If explicitly set to on or off, the input field will correct (on) or ignore (off) common spelling errors. If left to the defaults, it will inherit the behavior of the iOS settings.

Keyboard: Sets a predefined keyboard for providing input. By default, the input keyboard lets you type letters, numbers, and symbols. Choosing the option Number Pad will only allow numbers to be entered. Similarly, using Email Address constrains the input to strings that look like email addresses. Seven different keyboard styles are available.

Appearance: Changes the appearance of the keyboard to look more like an alert view (which you’ll learn about in a later hour).

Return Key: If the keyboard has a Return key, it is set to this label. Values include Done, Search, Next, Go, and so on.

Auto-Enable Return Key: Disables the Return key on the keyboard unless the user has entered at least a single character of input into the field.

Secure: Treats the field as a password, hiding each character as it is typed.

Of the three fields that we’ve added to the view, the Number field can definitely benefit from setting an input trait. With the Attributes Inspector still open, select the Number field in the view, and then choose the Number Pad option within the Keyboard pop-up menu (see Figure 4).

Figure 4. Choosing a keyboard type will help constrain a user’s input.

You may also want to alter the capitalization and correction options on the other two fields and set the Return key to Done. Again, all of this functionality is gained “for free.” So, you can return to Interface Builder to experiment all you want later on.

Connecting to the Outlets

The first three fields of the view are now finished and ready to be connected to their variables back in Xcode. To connect to the outlets defined earlier, Control-drag from the File’s Owner icon in the Document window to the first field (“Place”) either in the view window or within the Document window’s view hierarchy. When prompted, choose thePlace from the pop-up list of outlets, as shown in Figure 5.

Figure 5. Connect each field to its corresponding outlet.


Repeat the process for the Verb and Number fields, connecting them to the theVerb and theNumber instance variable outlets. The primary input fields are connected.

Now we’re ready to move on to the next element of the user interface: text views.

Copy and Paste

Your text entry areas will automatically gain copy and paste without needing to change anything in your code. For advanced applications, you can override the protocol methods defined in UIResponderStandardEditActions to customize the copy, paste, and selection process.

Other  
  •  Building Android Apps : Controlling the Phone with JavaScript (part 3) - Accelerometer
  •  Building Android Apps : Controlling the Phone with JavaScript (part 2) - Geolocation
  •  Building Android Apps : Controlling the Phone with JavaScript (part 1) - Beep, Vibrate, and Alert
  •  Building Your First Windows Phone 7 Application (part 5) - Styling Your Application
  •  Building Your First Windows Phone 7 Application (part 4) - Customizing Your First Windows Phone Application
  •  Building Your First Windows Phone 7 Application (part 3) - Writing Your First Windows Phone Code
  •  Building Your First Windows Phone 7 Application (part 2) - Using Your First Windows Phone Silverlight Controls
  •  Building Your First Windows Phone 7 Application (part 1) - Creating a Windows Phone Project
  •  Introducing Windows Phone 7 and the Windows Phone Platform
  •  Windows Phone Application Platform
  •  iPhone Application Development : Basic User Input and Output
  •  Mobile Phone Game Programming : A Quick J2ME Primer
  •  Mobile Phone Game Programming : Java As a Mobile Game Platform
  •  Mobile Phone Game Programming : Getting to Know Mobile Platforms
  •  Mobile Application Security : The Apple iPhone - Local Data Storage: Files, Permissions, and Encryption
  •  Mobile Application Security : The Apple iPhone - Permissions and User Controls
  •  iPhone Application Developmen : Using the View-Based Application Template (part 3)
  •  iPhone Application Developmen : Using the View-Based Application Template (part 2) - Preparing the View Controller Outlets and Actions
  •  iPhone Application Developmen : Using the View-Based Application Template (part 1)
  •  Mobile Application Security: Application Format
  •  
    Top 10
    Ipad : Wireless Sync Using the MobileMe Service (part 4) - Using MobileMe After Setup, How to Cancel Your MobileMe Account
    Ipad : Wireless Sync Using the MobileMe Service (part 3) - Set Up Your iPad to Access Your MobileMe Account
    Ipad : Wireless Sync Using the MobileMe Service (part 2) - Set Up MobileMe on Your Windows PC
    Ipad : Wireless Sync Using the MobileMe Service (part 1) - Sign up for the MobileMe Service, Set Up MobileMe on Your Mac
    Ipad : Wireless Sync of Your Google or Exchange Information (part 2) - Working With the Google or Exchange Contacts and Calendar on your iPad
    Ipad : Wireless Sync of Your Google or Exchange Information (part 1) - Set Up your iPad to Access Your Google or Exchange Account
    Windows Vista : Scripting and Automation - Object References (part 4) - Decipher Script Errors
    Windows Vista : Scripting and Automation - Object References (part 3) - How to Manage Windows Services, How to Write CGI Scripts for Web Servers
    Windows Vista : Scripting and Automation - Object References (part 2) - How to Use the Network, How to Control Internet Explorer, How to Use Command-Line Parameters
    Windows Vista : Scripting and Automation - Object References (part 1) - How to Run Applications, How to Access the, How to Manipulate Files Registry
    Most View
    Windows 7 : Installing and Running Your Software (part 1)
    Windows Server 2008 : Securing Internet Information Services 7.5
    Microsoft XNA Game Studio 3.0 : Getting Player Input - Reading a Gamepad
    Magix Photo Story On DVD MX Deluxe
    100 Windows Speed-Up Tips (Part 7) - Five ways Jump Lists can save your time
    Programming .NET Components : Visual Studio 2005 and Security
    Windows Vista : Trim the Fat (part 4) - Shut Down Windows Quickly
    Programming Microsoft SQL Server 2005 : An Overview of SQL CLR - CLR Triggers
    Mobile Application Security : Windows Mobile Security - Development and Security Testing (part 3)
    IIS 7.0 : Implementing Access Control - NTFS ACL-based Authorization & URL Authorization
    Defensive Database Programming with SQL Server : Using TRY...CATCH blocks to Handle Errors
    Eclipse Stealth FX812R795 Extreme with Eclipse Stealth Flight Pack
    Windows Server 2008 : Configure NAP
    Adobe Flash Catalyst CS5 : Using the Drawing Tools (part 1) - Set strokes and fills
    Phone Business: The Age Of Convergence
    Mac - That Syncing Feeling
    Is It Time To Ditch Windows Search? (Part 3) - Search across the LAN
    Windows Server 2008 R2 monitoring and troubleshooting : Event Viewer - Configuring event-based tasks & Setting up event log forwarding
    How To Put Together A Good Home Network (Part 3)
    Hacker Zone (Part 1) - Build your own Cyanogen-Mod ROM with CMC, Manage files in Recovery Mode