Programming in Objective-C 2.0 edition phần 9 pps

59 442 0
Programming in Objective-C 2.0 edition phần 9 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

463 Your First iPhone Application Figure 21.4 New iPhone project iPhone_1 is created. Returning to your New Project window, select Window-Based Application in the top rightmost pane and then click on the Choose button.When next prompted to enter the project name (in the Save As box), enter the text iPhone_1 and click Save.This also be- comes your application’s name by default. As you know from previous projects you cre- ated with Xcode, a new project will now be created for you that contains templates for files you’ll want to use.This is shown in Figure 21.4. Depending on your settings and previous uses of Xcode, your window might not ap- pear precisely as depicted in Figure 21.4.You can choose to follow along with whatever your current layout resembles or else try to make it match the figure more closely. In the top-left corner of your Xcode window, you see a drop-down labeled with your current selection of SDK and Active Configuration. Because we’re not developing your application to run directly on the iPhone, you want the SDK set up to run with the iPhone simulator and the Configuration to be set to Debug. If the drop-down is not la- beled Simulator | Debug, set the appropriate options as shown in Figure 21.5. Entering Your Code Now we’re ready to modify some of your project files. Notice that a class called project- name AppDelegate.h and project-name AppDelegate.m were created for you, where in this example project-name is iPhone_1.The work of handling the various buttons and labels in the type of Window-based application you’re creating gets delegated to a class called project- name AppDelegate, or in this case, iPhone_1AppDelegate. In this class we’ll define meth- Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 464 Chapter 21 Writing iPhone Applications Figure 21.5 iPhone_1 project with SDK and Configuration options set. ods to respond to actions that occur in the iPhone’s window, such as the pressing of a but- ton or the movement of a slider.As you’ll see, it’s in the Interface Builder application that you make the actual connection between these controls and the corresponding methods. The class will also have instance variables whose values correspond to some control in your iPhone’s window, such as the name on a label or the text displayed in an editable text box.These variables are known as outlets, and like your action routines, in Interface Builder you connect your instance variables to the actual control in the iPhone’s window. For our first application, we need a method that responds to the action of the pressing of the button labeled 1.We also need an outlet variable that contains (among other informa- tion) the text to be displayed in the label that we create at the top of the iPhone’s window. Edit the file iPhone_1AppDelegate.h to add a new UILabel variable called display and declare an action method called click1: to respond to the pressing of the button. Your interface file should look as shown in Program 21.1. (The comment lines automati- cally inserted at the head of the file are not shown here.) Program 21.1 iPhone_1AppDelegate.h #import <UIKit/UIKit.h> @interface iPhone_1AppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 465 Your First iPhone Application UILabel *display; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UILabel *display; - (IBAction) click1: (id) sender; @end Notice that iPhone applications import the header file <UIKit/UIKit.h>.This header file, in turn, imports other UIKit header files, in a similar way that the Foundation.h header file imported other header files you needed, such as NSString.h and NSObject.h. If you want to examine the contents of this file, you have to hunt a bit. Here’s where it’s installed on my system at the time of this writing: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulat or2.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIKit.h . The iPhone_1AppDelegate class now has two instance variables.The first is a UIWindow object called window.That instance variable is created automatically when you create the project, and it references the iPhone’s main window.You added another instance variable belonging to the UILabel class called display.This will be an outlet variable that will be connected to a label.When you set this variable’s text field, it updates the corre- sponding text for the label in the window. Other methods defined for the UILabel class allow you to set and retrieve other attributes of a label, such as its color, the number of lines, and the size of the font. You’ll want to use other classes in your interface as you learn more about iPhone pro- gramming that we won’t describe here.The names of some of these give you a clue as to their purpose: UITextField, UIFont, UIView, UITableView, UIImageView, UIImage, and UIButton. Both the window and display instance variables are outlets, and in the property decla- rations for these two variables, note the use of IBOutlet identifier. IBOutlet is really defined as nothing in the UIKit header file UINibDeclarations.h. (That is, it is literally replaced by nothing in the source file by the preprocessor.) However, it’s needed because Interface Builder looks for IBOutlet when it reads your header file to determine which of your variables can be used as outlets. In the interface file, note that we declare a method called click1: that takes a single argument called sender.When the click1: method is called, the method will be passed information related to the event in this argument. For example, if you had a single action routine that you used to handle the pressing of different buttons, the argument can be queried to ascertain the particular button that was pressed. The click1: method is defined to return a value of type IBAction. (This is defined as void in the UINibDeclarations.h header file.) Like IBOutlet, Interface Builder uses this Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 466 Chapter 21 Writing iPhone Applications identifier when it examines your header file to identify methods that can be used as ac- tions. Now it’s time to modify the corresponding iPhone_1AppDelegate.m implementation file for your class. Here you synthesize the accessor methods for your display variable (the window access methods are already synthesized for you) and add the definition for your click1: method. Edit your implementation file so that it resembles the one shown in Program 21.1. Program 21.1 iPhone_1AppDelegate.m #import ““iPhone_1AppDelegate.h”” @implementation iPhone_1AppDelegate @synthesize window, display; - (void) applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after application launch [window makeKeyAndVisible]; } -(IBAction) click1: (id) sender { [display setText: @”1”]; } - (void) dealloc { [window release]; [super dealloc]; } @end The applicationDidFinishLaunching: method is automatically called by the iPhone runtime system once; as its name implies, your application has finished launching.This is the place where you can initialize your instance variables, draw things on the screen, and make your window visible to display its contents.This last action is done by sending the makeKeyAndVisible message sent to your window at the end of the method. The click1: method sets the outlet variable display to the string 1 by using UILabel’s setText: method.After you connect the pressing of the button to the invoca- tion of this method, it can perform the desired action of putting a 1 into the display in the iPhone’s window.To make the connection, you must now learn how to use Interface builder. Before you do that, build the program to remove any compiler warning or error messages. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 467 Your First iPhone Application Designing the Interface In Figure 21.4, and in your Xcode main window, notice a file called MainWindow.xib.An xib file contains all the information about the user interface for your program, including information about its windows, buttons, labels, tab bars, text fields, and so on. Of course you don’t have a user interface yet! That’s the next step. Double-click on the MainWindow.xib file.This causes another application, called Inter- face Builder, to launch.You can also access the XIB file from the Resources folder of your project. When Interface Builder starts, you get a series of windows drawn on your screen, as depicted in Figures 21.6, 21.7, and 21.8.The actual windows that are opened might differ from the figures. The Library window provides a palette of controls that you can use for your interface. This window is depicted in Figure 21.6 in one of its display formats. The MainWindow.xib window (Figure 21.7) is the controlling window for establishing connections between your application code and the interface, as you’ll see shortly. Figure 21.6 Interface Builder Library window. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 468 Chapter 21 Writing iPhone Applications Figure 21.7 Interface Builder MainWindow.xib. The window simply labeled Window shows the layout of the iPhone’s main window. Because you haven’t designed anything for your iPhone’s window yet, it starts out empty, as shown in Figure 21.8. The first thing we’ll do is set the iPhone’s window to black.To do this, first click inside the window labeled Window. Now, select Inspector from the Tools menu.This should bring up the Inspector window, as shown in Figure 21.9. Make sure your Inspector window is labeled Window Attributes, as shown in Figure 21.8. If it isn’t, click on the leftmost tab in the top tab bar to get the correct window dis- played. If you glance down to the View section of the window, you see an attribute labeled Background. If you double-click inside the white-filled rectangle next to Background, it brings up a color picker for you. Choose black from the picker, which changes the rectan- gle next to Background attribute in the Inspector from white to black (see Figure 21.10). If you take a look at the window labeled Window, which represents the iPhone’s display window, you see that it’s been changed to black, as shown in Figure 21.11. You can now close the Colors window. You create new objects in your iPhone interface window by click-dragging an object from the Library window into your iPhone window. Click-drag a Label now. Release the mouse when the label is near the center of the window, close to the top, as shown in Figure 21.12. Blue guide lines appear in your window as you move the label around inside your win- dow. Sometimes they appear to help you align objects with other objects previously placed in the window.At other times, they appear to make sure your objects are spaced far enough apart from other objects and from the edges of the window, to be consistent with Apple’s interface guidelines. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 469 Your First iPhone Application Figure 21.8 Interface Builder iPhone window. Figure 21.9 Interface Builder Inspector window. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 470 Chapter 21 Writing iPhone Applications Figure 21.10 Changing the window’s background color. Figure 21.11 Interface window changes to black. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 471 Your First iPhone Application You can always reposition the label in the window at any time in the future by click- dragging it to another spot inside the window. Let’s now set some attributes for this label. In your window, if it’s not currently se- lected, click the label you just created to select it. Notice that the Inspector window auto- matically changes to give you information about the currently selected object in your window.We don’t want any text to appear by default for this label, so change the Text value to an empty string. (That is, delete the string Label from the text field shown in the Inspector’s window.) For the Layout attribute, select Right-justified for the alignment. Finally, change the background color for the label to blue (or any other color you choose), like you changed the window’s background color to black.Your Inspector window should resemble Figure 21.13. Now let’s change the size of the label. Go back to Window and simply resize the label by pulling out along its corners and sides. Resize and reposition the label so that it looks like the one shown in Figure 21.14 Now we add a button to the interface. From the Library window, click-drag a Round Rect Button object into your interface window, placing it toward the lower-left corner of the window, as shown in Figure 21.15.You can change the label on the button in one of Figure 21.12 Adding a label. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 472 Chapter 21 Writing iPhone Applications two ways: by double-clicking on the button and then typing your text, or by setting the Title field in the Inspector window. Either way you choose, make you window match the one shown in Figure 21.15. Now we have a label that we want to connect to our display instance variable in our program so that when we set the variable in our program the label’s text will be changed. We also have a button labeled 1 that we want to set to invoke our click1: method whenever it gets pressed.That method sets the value of display’s text field to 1.And be- cause that variable will be connected to the label, the label will then be updated.As a re- cap, here’s the sequence we want to set up: 1. The user presses the button labeled 1. 2. This event causes the click1: method to be invoked. 3. The click1: method changes the text of the instance variable display to the string 1. 4. Because the UILabel object display connects to the label in the iPhone’s window, this label updates to the corresponding text value, or to the value 1. Figure 21.13 Changing the label’s attributes. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... Writing iPhone Applications @property (nonatomic, retain) UIWindow *window; @property (nonatomic, retain) Fraction_CalculatorViewController *viewController; @end The UIWindow instance variable window serves the same purpose as in the first program example: it represents the iPhone’s window.The Fraction_CalculatorViewController instance variable represents the view controller that will manage all the interaction... file followed immediately by the corresponding implementation file Program 21.2 Fraction.h Interface File #import @interface Fraction : NSObject { int numerator; int denominator; } @property int numerator, denominator; -(void) -(void) -(Fraction -(Fraction -(Fraction -(Fraction -(void) -(double) -(NSString @end print; setTo: (int) n over: (int) d; *) add: (Fraction *) f; *) subtract:... are housekeeping variables for building the fractions (currentNumber, for building the string for the display (displayString).There is also a Calculator object (myCalculator) that can perform the actual calculation between the two fractions.We will associate a single method called clickDigit: to handle the pressing of any of the digit keys 0 -9 Finally, we define methods to handle storing the operation... -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; else return 1.0; } -(NSString *) convertToString; { if (numerator == denominator) if (numerator == 0) return @”0”; else return @”1”; else if (denominator == 1) return [NSString stringWithFormat: @”%i”, numerator]; else return [NSString stringWithFormat: @”%i/%i”, numerator, denominator]; } // add a Fraction to the... gain their etymology from the discipline of objectoriented programming In the latter case, I provide the meaning of the term as it specifically applies to the Objective-C language abstract class A class defined to make creating subclasses easier Instances are created from the subclass, not of the abstract class See also concrete subclass accessor method A method that gets or sets the value of an instance... definitions for a class and can be used to add new methods to an existing class character string A null-terminated sequence of characters class A set of instance variables and methods that have access to those variables After a class is defined, instances of the class (that is, objects) can be created class method A method (defined with a leading + sign) that is invoked on class objects See also instance... 21 Writing iPhone Applications [displayString appendString: @” = “]; [displayString appendString: [myCalculator.accumulator convertToString]]; [display setText: displayString]; currentNumber = 0; isNumerator = YES; firstOperand = YES; [displayString setString: @””]; } -(IBAction) clickClear: (id) sender { isNumerator = YES; firstOperand = YES; currentNumber = 0; [myCalculator clear]; [displayString setString:... currently keying in the numerator or the denominator of that operand When a digit button is pressed on the calculator, we set it up so that some identifying information will be passed to the clickDigit: method to identify which digit button was pressed.This is done by setting the button’s attribute (using Interface Builder’s Inspector) called tag to a unique value for each digit button In this case,... also adds the digit to the current display string that’s kept in the variable displayString, and updates the display: -(void) processDigit: (int) digit { currentNumber = currentNumber * 10 + digit; [displayString appendString: [NSString stringWithFormat: @”%i”, digit]]; [display setText: displayString]; } When the = key is pressed, the clickEquals: method gets invoked to perform the operation.The calculator... you do that, the sequence of steps we outlined and the connections you made should result in the display of the string 1 in the label at the top of the display, as shown in Figure 21.2 Figure 21. 19 Finishing the connection An iPhone Fraction Calculator The next example is a bit more involved, but the concepts from the previous example equally apply.We’re not going to show all the steps to create this . Application Designing the Interface In Figure 21 .4, and in your Xcode main window, notice a file called MainWindow.xib.An xib file contains all the information about the user interface for your program, including information. should bring up the Inspector window, as shown in Figure 21 .9. Make sure your Inspector window is labeled Window Attributes, as shown in Figure 21 .8. If it isn’t, click on the leftmost tab in the. for your interface. This window is depicted in Figure 21 .6 in one of its display formats. The MainWindow.xib window (Figure 21 .7) is the controlling window for establishing connections between

Ngày đăng: 12/08/2014, 23:22

Từ khóa liên quan

Mục lục

  • About the Author

  • About the Technical Reviewers

  • We Want to Hear from You!

  • Reader Services

  • Introduction

    • What You Will Learn from This Book

    • How This Book Is Organized

    • Acknowledgments

    • The Objective-C 2.0 Language

      • Programming in Objective-C

        • Compiling and Running Programs

        • Explanation of Your First Program

        • Displaying the Values of Variables

        • Summary

        • Exercises

        • Classes, Objects, and Methods

          • What Is an Object, Anyway?

          • Instances and Methods

          • An Objective-C Class for Working with Fractions

          • The @interface Section

          • The @implementation Section

          • The program Section

          • Accessing Instance Variables and Data Encapsulation

          • Summary

Tài liệu cùng người dùng

Tài liệu liên quan