iPhone FirstApp: Guess the number - Part 1

The first source that I rose in my hands was written in Basic and consisted of a few lines of code, for enlightening me. It was a simple game that generates a random number from 1 to 10 and, through keyboard input, verify that the number entered was Maggioni, less than or equal to the random number. Despite its rough simplicity remains, for me, one of the best examples - simple, fun and practical - to explain to those who do not know anything about programming what is meant actually for "computer program". So I decided to propose it for Apple iPhone, maybe will help someone ...

In this post we will achieve a particular version of "Guess the number" and call FirstApp. Later rewrite the same application with different methods, such as manually creating a UIView or leaving from Interface Builder.

The application already made, if you just want to download, is available on my Google Code repository:

1 - We start

Open XCode, select New Project from the File menu and choose, for this version, from the classic View-Based Application (the next time we start from Window-Based Application to obtain the exact same result). Call the project FirstApp and save it where it suits you most.

XCode New Project

As you can see I'm still using the version of XCode for SDK 2.2.1, SDK 3.0 is not because they are still "very" stable. Keep in mind this image as the new version of XCode some templates are not quite identical, and some things will change. But for now you do not need to worry about this unless they were already using the latest release of XCode.

viewcontroller In this version we will use Interface Builder and then, first, we will draw our user interface. Let us open the Resources folder and double click on FirstAppViewController.xib . This file is right in Interface Builder, as the file MainWindow.xib (see also the file extension I nterface B uilder X).
Any other controllers are always placed in this folder. The remaining folders contain all the other files of our application and, in particular, we will work a lot on those in the Classes folder.
Going back to Interface Builder we are faced with a blank screen that represents our View , the container will be placed where objects of our UIKit user interface. This visual object we are looking at using Interface Builder is connected to a file FirstAppViewController.m (and. h) present in the Classes folder.

library In the Library window are all visual components to create standard interfaces, pleasant and accessible on our Apple iPhone.
These are easily sorted by type (see the blue folder at the top). To include them in our View, simply select the component from the Library and drag it into the fienstra our window View, where we could place it, resize it and configure it at will (all things code also feasible, as we shall see shortly).
), un campo testo per l'inserimento del numero da indovinare ( UITextField ) e – finalmente – un semplice bottone ( UIButton ) per verificare se abbiamo indovinato: Before continuing, it is the first time you work with Interface Builder, a little fun 'trying out the various components, and when it gets too much, make sure you get something like the image shown below, which is made with a title the component UINavigationBar , an introductory text ( UILabel ), a text field for entering the number to guess ( UITextField ) and - finally - a simple button ( UIButton ) to see if we guessed:

view

The setting of the components in Interface Builder through a particular window is always divided into four tabs: attributes, connections, size and identity, a sort of "inspector" of the components. Depending on the selected component Identity dialog is configured with the appropriate characteristics for the component. If we select the UINavigationBar , for example, we have all the possible settings for this component type.

ispettore

2 - Code

Now that we have established our position and visual components for the interface, let's write a little 'code to manipulate. First of all let's open the file FirstAppViewController.he become so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/ /
/ / FirstAppViewController.h
/ / FirstApp
/ /
/ / Created by Giovambattista Fazioli on 19/06/09.
/ / Copyright Saidmade Ltd. 2009. All rights reserved.
/ /

# Import <UIKit/UIKit.h>

UIViewController { @ Interface FirstAppViewController: UIViewController {
IBOutlet UITextField * number;
IBOutlet UIButton * button;
numeroACaso int;
}

IBAction ) controllaNumero; - (IBAction) getNumber;

@ End

Lines 12, 13 and 14 define the "variables" of our game. di Interface Builder. The first two are pointers to our graphics included with Interface Builder: the text box and button. IBOutlet , davati type, serves to create a link, a reference, to the interface .xib Interface Builder. In fact, if we wanted to create our franchisees components through code without going through Interface Builder, just delete the IBOutlet , as redundant. Line 17, however, defines a method (a post-event) that we want to trigger when the user clicks the button. In this file. H (header files) we performed only definitions. The implementation of the actual code is in the corresponding file. M: FirstAppViewController.m . Control-clicking is ALT + UP ARROW switches alternately. H file to the file. M. Let's go then to edit FirstAppViewController.m . First of all to delete comments meotdo viewDidLoad (33 th row or so) and let's become:

1
2
3
4
5
6
7
/ / Implement viewDidLoad to do additional setup after loading the view, Typically From A nib.
void ) viewDidLoad { - (Void) {viewDidLoad
; [Super viewDidLoad];

+ arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%;
"Numero pensato %d" , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
}

viewDidLoad is one of the methods invoked when the application starts. di jQuery . If you want is a little 'to the document onload Javascript or $(document).ready() to jQuery . I added the lines that are 5 and 6. The 5, in particular, creates a random number from 1 to 10! The line number 6, however, is only for debugging and prints the number generated on the console. : Now we write the code (the impementazione) method controllaNumero() we defined in the file FirstAppViewController.h :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
IBAction ) controllaNumero { - (IBAction) {getNumber
"Premuto bottone di controlla numero" ) ; NSLog (@ "Pressed button control number");

[ numero.text integerValue ] ; numeroInserito = int [numero.text integerValue];
message; NSString * message;

"Il numero inserito è %d" , numeroInserito ) ; NSLog (@ "The number entered is% d", numeroInserito);

numeroInserito < numeroACaso ) { if (numeroInserito <numeroACaso) {
"Troppo basso..." ; message = @ "Too low ...";
( numeroInserito > numeroACaso ) { } Else if (numeroInserito> numeroACaso) {
"Troppo alto..." ; message = @ "Too high ...";
( numeroInserito == numeroACaso ) { } Else if (numeroInserito numeroACaso ==) {
"Bravo hai indovinato" ; message = @ "Bravo, you guessed it";
+ arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%;
"Numero pensato %d" , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
}

[ [ UIAlertView alloc ] initWithTitle : @ "Responso" message : message delegate : nil cancelButtonTitle : @ "OK" otherButtonTitles : nil ] ; UIAlertView alertMessaggio * = [[UIAlertView alloc] initWithTitle: @ "Response" message: message delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil];
; [AlertMessaggio show];
; [AlertMessaggio release];

"" ; numero.text @ = "";
}

This code, the last write before going back to Interface Builder, we can define it as the heart of the system, or better of the game. In fact, it checks whether the number entered in the text field ( UITextField ) is less than, greater than or equal to the number "thought" from our iPhone. Depending on the outcome shows an alert. Line 2, as always, is only for debugging and prints a message on the console when we click the button. Line 4, however, is interesting, and this transforms the textual content of our textbox to an integer number. This is necessary to compare the random number numeroACaso with the number entered by the user. In Objective-C, as in C, there are no implicit type conversions, such as other high level languages ​​that do not support the strict sense of the variables in tipizazzione. In some languages, in fact, you can compare strings and integers without performing any explicit conversion, or casting.

Line 5 prepares a pointer to a string message that the answer will be displayed nell'alert. Lines 9 to 17 control the number entered by the user with the random number and draw the necessary conclusions. I purposely put these " if "brutal to make the code as clear as possible. Alternatively we could use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
( ( numeroInserito - numeroACaso ) < 0 ) ? - 1 : ( ( numeroInserito - numeroACaso ) ? 1 : 0 ) ; Decision = int ((numeroInserito - numeroACaso) <0)? - 1: ((numeroInserito - numeroACaso)? 1: 0);

decisione ) { switch (decision) {
1 : houses - 1:
"Troppo basso..." ; message = @ "Too low ...";
break;
: case 1:
"Troppo alto..." ; message = @ "Too high ...";
break;
: case 0:
"Bravo hai indovinato" ; message = @ "Bravo, you guessed it";
/ / Start over ...
+ arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%;
"Numero pensato %d" , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso);
break;
}

We combine the code with Interface Builder

Let us now return to Interface Builder, click the file always FirstAppViewController.xib . What we're going to do now allow you to link the visual interface with Interface Builder and prepared the code we've written, especially with the components highlighted with IBOutlet . The components that we need to link our code to have the textbox and the button, as defined in the interface definition files FirstAppViewController.h . . To these we gave the name of the respective numero and bottone . From Interface Builder we have various ways to link visual components with the code, one of the simplest is to click the right mouse button on our visual component, such as the text field ( UITextField ):

iboutlet

This window is different for each component, shows us all that we can "link" with the code. In particular we are interested in the last item, the section Referencing Outlets New Referencing Outlet. Click on the "circle" to the right and - holding down the mouse button - drag the window princiaple FirstAppViewController.xib FirstAppViewController over the icon (File's Owner):

viewcontroller-link

: Releasing the mouse button a menu will appear with the list of all the "variables" (properties) IBOutlet and defined as UITextField :

menu-outlet

In our case we select numero . We repeat the exact same procedure for the button, with the addition that the latter had also called an event: - (IBAction) controllaNumero; . At the end otteremo:

ibaction

Conclusions

If you did everything correctly we're done! Our play is ready. If you can download the complete source here . Obviously this is just an example and is missing some details to make it a real application, the 57 × 57 icons to control the input number and other details yet. The development process described here can be varied, for example via Interface Builder only once, ie at the end: Before you write all the code and then you go to Interface Builder to link objects. In this example we have moved on over to Interface Builder to draw the outline of our interface, being the simplest application.

Next time we will see how to implement the medisimo "play" without using Interface Builder.

There are no comments for this post

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL 


Stop SOPA