let'sgotoseethisshow(反问疑问句和反问句)

How To Make iPhone Apps – Creating The Demo App With XCode And Interface Builder
Welcome to the final part of my series on How To Make iPhone Apps with no programming experience – where we’ll turn even the non-programmer into an iOS developer! Here’s the
in case you missed it.
In this part, we’ll put all of the things we learned in the previous parts into practice and build a dice roll app.
Updated Jan 13, 2013: Corrected some typos and added more clarification for where the code goes.
Updated Oct 27, 2013: Adding more steps and clarification based on reader feedback.
Updated Sept 25, 2013: This article has been updated for XCode 5. If you’re looking for the XCode 4 version, click
Seriously. If you’ve made it through all four of the previous parts in the series then the hard part is over. In this part, we’re going to have some fun and put together all the things we’ve learned into a dice rolling app. Let’s get to it!
Fire up XCode and let’s create our project! Go to File->New->Project… and you’ll be greeted with a menu where you can select a few different types of projects.
Select “Single View Application”.
The product name is what you’re going to name your project. Don’t worry, you can still set the app name which appears underneath your app icon later.
The organization name should represent you or your company.
And you’ll notice that when you type those two fields in, it’ll form a Bundle Identifier for you.
This is a unique identifier for your application and it is usually in the format of com.organization_name.product_name.
The idea is that if you release another product, it’ll have an identifier com.organization_name.next_product_name.
Select iPhone for the device drop-down because our demo app will only be for the iPhone.
And with that, click Next and choose a location to save your project!
Now you’ll be presented with the XCode interface that we learned about in our .
Let’s take a look at what files are created for us:
We see an AppDelegate.m and AppDelegate.h. Remember what you learned about ? Together they form a class!
Ok, so we’ve got a class called AppDelegate however, it’s not like a normal class that we define and
create instances of it. The AppDelegate class is the entry point to your application.
All we really do in the AppDelegate add some custom code (if we need to) to certain events like when the app starts, terminates, gets sent to the background or returns to the foreground.
The next class we’ve got is ViewController. If you remember from our , a view controller is what XCode calls the controller role in MVC.
We also have a storyboard which defines the view for our view controller and designates it as the starting view controller for our app. This is an interface builder file so when you click it, the editor area will reveal the visual designer.
Here’s how the AppDelegate, View (Storyboard) and ViewController interact together:
If you remember the model-view-controller pattern, the view controller handles the communication back and forth between the view and model, however there’s no model class in our XCode project currently!
Let’s create our model class now.
Right click in the project navigation and choose “New File…”
This will bring up the template selector. Select “Objective-C” class.
Let’s name our data model “DiceDataController” and make it subclass NSObject.
XCode will create a DiceDataController.h and DiceDataController.m file for us to represent our class. Open up the header file and let’s add a method that other classes can call in order to generate a dice roll.
@interface DiceDataController : NSObject&- (int)getDiceRoll;&@end
DiceDataController.h
If you remember from Part 1, this is a instance method called “getDiceRoll” that we expect to return an integer when we call it.
Now let’s flip over to the implementation file, DiceDataController.m, where we’ll write the code for the getDiceRoll method:
12345678910
@implementation DiceDataController&- (int)getDiceRoll{&&&&int roll = (arc4random() % 6) + 1;&&&&&&&&return roll;}&@end
DiceDataController.m
In this method, we’re declaring an int variable named “roll” and assigning it a number from the equation:
(arc4random() % 6) + 1
arc4random() is a math function that will give you a random integer and by modding it by 6, we’ll get an int from 0 to 5. Then we add 1 to get our desired die roll range of 1 to 6. Finally, we return the roll variable as the output of the method.
Now we let our controller know about our model. Remember, in MVC the controller acts as the communication layer between the model and the view.
So go to ViewController.h (header file) and we’re going to add an import statement for our model so that ViewController.m knows about what methods are available for it to call in the model.
#import &UIKit/UIKit.h&#import "DiceDataController.h"&@interface ViewController : UIViewController
ViewController.h
Next, we’ll create a property in the controller to hold an instance of the model.
#import &UIKit/UIKit.h&#import "DiceDataController.h"&@interface ViewController : UIViewController&@property (strong, nonatomic) DiceDataController *model;&@end
ViewController.h
Now that the property is created, we need to assign it an instance of our model before we can use it, so open up ViewController.m.
And in the ViewDidLoad method, we’ll allocate a new instance of our DiceDataController class and assign it to the property that we just created.
@implementation ViewController&- (void)viewDidLoad{&&&&[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.&&&&&&&&self.model = [[DiceDataController alloc] init];}
ViewController.m
Now our model property is ready to use when we need it.
Let’s create a UIView to show our die images.
Remember that a UIView is an Apple class that we can use to display things to the user. Go to your project navigator, right click and select New File. Make sure it’s a subclass of UIView and name it DieView.
Each DieView is going to show one die. Later when we construct our user interface (UI), we’ll add two instances of DieView on it to represent the pair of dice.
Go into the header file of DieView first (DieView.h). We’re going to declare a method that will allow another class to tell our UIView to display a die graphic of a number that we pass into the method.
#import &UIKit/UIKit.h&&@interface DieView : UIView&- (void)showDie:(int)num;&@end
In the code above, we’ve declared a instance method called showDie that accepts one integer parameter and returns nothing.
Our DieView is going to display an image so we’ll need a UIImageView property to represent that image. Let’s create a new property in our header file.
12345678910111213
#import &UIKit/UIKit.h&&@interface DieView : UIView&#pragma mark Properties&@property (nonatomic, strong) UIImageView *dieImage;&#pragma mark Methods&- (void)showDie:(int)num;&@end
In the code above, we’ve called our property, dieImage.
Notice that there are two lines that start with “#pragma mark”. These are for the programmer to organize his/her code into sections for readability and navigation.
Adding the die images
Before we can display any die images, we need to add the images to our XCode project!
Note: The images can be found in the .
Click the “images.xcassets” in your Project Navigator to open up your asset catalog.
Right click in an empty area in your asset listing and choose “Import”
Then browse for the images which you download from the link above and add them to your project.
Note: If you’re using XCode 4, you can simply place the images in your project folder and drag them into the Project Navigator area of your XCode project. And you should also be following the XCode 4 version of this article instead!
Implementing DieView
Now, let’s jump into the implementation file and code our method (DieView.m).
In our showDie method, we’re going to check if our dieImage property is nil. If it is, that means that we haven’t assigned any UIImageView object to this property yet, so we have to create a new UIImageView object and assign it to the property.
Just to remind you, we’re going to use this UIImageView to display an image of the die representing a number.
As part of creating a new UIImageView object and assigning it to the property, we also have to place that UIImageView object into the UIView so that it is visible to the user. We do that using the “addSubview” method of the UIView as you can see below:
1234567891011121314151617181920212223242526272829303132333435
@implementation DieView&- (id)initWithFrame:(CGRect)frame{&&&&self = [super initWithFrame:frame];&&&&if (self) {&&&&&&&&// Initialization code&&&&}&&&&return self;}&/*// Only override drawRect: if you perform custom drawing.// An empty implementation adversely affects performance during animation.- (void)drawRect:(CGRect)rect{&&&&// Drawing code}*/&- (void)showDie:(int)num{&&&&if (self.dieImage == nil)&&&&{&&&&&&&&self.dieImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];&&&&&&&&&&&&&&&&[self addSubview:self.dieImage];&&&&}&&&&&&&&NSString *fileName = [NSString stringWithFormat:@"dice%d.png", num];&&&&&&&&self.dieImage.image = [UIImage imageNamed:fileName];}&@end
Remember that “self” refers to that instance of the DieView so “self.dieImage” is referring to it’s own dieImage property and “[self addSubview:self.dieImage]” is calling it’s own “addSubview” method and adding the UIImageView to it’s own view.
The next thing we do in that method is to construct the filename of the die image we should show. If you added the dice images to the project, you’ll notice that they were named “dice” followed by a number representing the numeric value of the die. Also, in this method, we accept a parameter of int type that specifies which die image we should show.
So in order to get the filename of the die image we want, we can simply concatenate the string “dice” with the int value that is passed in.
The string method “stringWithFormat” returns an NSString but allows you to specify a format that has some wildcard placeholders in it, and also specify some variables to put into those placeholders. In the line above, “[NSString stringWithFormat:@”dice%d.png”, num]”, the placeholder is “%d” and the variable we’re putting into that placeholder is “num”.
The resulting string that is assigned to our fileName variable will be dice[num].png where [num] is whatever number is passed into the method.
We’re almost done with our DieView class!
The last line assigns an image to our UIImageView element. The UIImageView object has a property called image that accepts a UIImage. So we can create a UIImage using the “imageNamed” class method and passing in our desired filename.
At this point, your project will look something like below. (Don’t worry if your images aren’t in their own folder like in my screenshot).
When we created the project, XCode added a Storyboard file to our app which describes the view for the ViewController class. If you click on this Storyboard file, XCode will change the
to the Interface Builder designer.
Within this designer, we’ll drag and drop our user interface elements onto the screen and then expose those elements to the code so that we can access and manipulate these elements from ViewController.m.
First of all, let’s make sure we’re all on the same page. You should see something like this when you highlight Main.storyboard in the XCode Project Navigator:
Don’t worry if you see two panes instead of one. You can toggle it with the Assistant Editor view button in the upper right hand corner of XCode.
If you don’t see the library pane with the UI elements in the lower right hand corner, you may be looking at the wrong tab of the library pane.
Adding the background
Let’s change the background of this view. You should’ve added the image assets to your asset catalog from an earlier step.
Type in “UIImageView” into the library search bar in the lower right hand corner (see screenshot below). This will filter the library for the UIImageView element and you can drag that element and drop it into your view. The UIElement will adjust to encompass the entire area and you should end up with a UIImageView like in the screenshot below:
If you can’t drop the UIImageView element onto the view, you may be in “zoomed out” mode. Double click any empty area on the storyboard to zoom back in and you should be able to drop elements onto the view.
In the upper right hand pane (the Inspector pane), there’s a field called “Image” with a dropdown that you can open up to find felt.png. Once you select felt.png, it will assign that image to the UIImageView that we just added to our view.
Adding the text labels
Next, we’ll want to add a UILabel to show text in our user interface. Like before, search for “UILabel” in the library search bar in the lower right corner and then drag and drop a UILabel element into our view.
Once you place the UILabel into the view, adjust the size/position of the UILabel by clicking and dragging one of the little handles (the white squares surrounding the label). Then change the text and font color in the Inspector Pane like below:
Adding the Roll button
Now let’s add a button. Search for “UIButton” and drag and drop a “Round Rect Button” element into the view. Change the button title to “Roll” and position it in the center, closer to the bottom of the view like so:
Adding the DieViews
The last thing we have to add to our view are the DieViews that we created earlier. Remember that DieView is a UIView so what we’re going to do is add two UIView elements to our interface and then tell Interface Builder that those two UIView elements are actually instances of our DieView class.
Let’s start by adding two UIView elements. Search for “UIView” in the lower right corner of XCode and drag a UIView onto the interface. You’ll probably need to resize it via the Size Inspector (see screenshot). I resized it to 90px height and 90px width.
You’ll have to add another UIView to the interface and resize it and reposition it beside the first UIView.
Now the next step is to tell Interface Builder that these two UIViews are actually DieViews and we do this through the Identity Inspector.
Click on one of the UIViews you added and over to the right, click the Identity Inspector tab (see screenshot below) and click the Class dropdown to select “DieView” as your Custom Class.
Do this for both of the UIViews you added and just like that, you have two instances of DieView in your interface.
We’re pretty much done with the user interface now. Check that your Objects list looks similar to this (I’ve renamed some of them so it’s easier to tell which item represents which UI element. You can rename yours too by clicking on an item in the Objects list and pressing enter):
One more thing you can do is change both DieView backgrounds to “clear” so that the die images that we’re going to display don’t show up against an ugly white background!
Now all we have to do is to hook up the user interface elements to our code so we can change what is displayed via code. This is a two step process:
-First we have to expose these elements to ViewController.m as properties and give them names so that we can refer to these elements from ViewController.m.
-Secondly, we have to handle the action of the user clicking the button and changing the images in the DieViews.
Ok, so let’s do the first:
IBOutlets: exposing interface elements as properties in ViewController
We can expose the UI elements we’ve created through Interface Builder by simply dragging and dropping. In the Navigator Pane, make sure that you’ve got ViewController.XIB selected so you should be seeing your user interface in the Editor Area. Next, make sure you have the Assistant Editor turned on so that your Editor Area is split into two panes.
The left pane is the user interface and the right pane is ViewController.h.
You’ll end up with something like this on your screen:
If you don’t have ViewController.h in the right pane, you can use the jump bar or the button in the corner of the right pane to select it.
Once you see that on your screen, it’s time to hold the “control” key, click on the sum UILabel item in the Objects list of Interface Builder and drag it over to the right pane, letting go right underneath the “@interface” heading.
You should see something like this:
When you let go, a little dialog will popup where you can name the IBOutlet that you just created. I’ve named it “sumLabel”.
Repeat the steps above to create an IBOutlet for both DieViews.
Remember to import “DieView.h” so that the class is recognized! (see below)
Your ViewController.h file should end up looking something like this:
The next step is to handle the scenario when the user taps the “Roll” button.
IBActions: Handling user interaction in ViewController
In order to add an event handler to our code to handle the button click, we can use the drag and drop technique again except this time, make sure that ViewController.m is opened on the right pane because remember, implementation code goes in the implementation file.
Once you have ViewController.xib opened on the left pane and ViewController.m opened on the right pane, you can once again hold down the ‘control’ key, click the button in the Objects list and drag to the right pane. Let go in a free area and you’ll get a popup to give your IBAction a name. I named mine “rollButtonClicked”.
So now we’ve created a method to handle the scenario of a user clicking the button. Let’s write the code for our method!
In Part 4, we instantiated the diceDataController property so now we can use it in our roll method.
First of all, go to the “rollButtonClicked” method of ViewController.m and let’s create two variables and assign them some random dice numbers:
- (IBAction)rollButtonClicked:(id)sender{&&&&int roll = [self.model getDiceRoll];&&&&int roll2 = [self.model getDiceRoll];}
ViewController.m
In the two lines above, we declare two int variables and call the getDiceRoll method of our data model to return two random dice numbers.
Next, we use the two DieView IBOutlet properties we created (the two DieViews we created in Interface Builder are assigned to these properties), and we call their respective “showDie” methods and pass in the random dice numbers:
- (IBAction)rollButtonClicked:(id)sender{&&&&int roll = [self.model getDiceRoll];&&&&int roll2 = [self.model getDiceRoll];&&&&&&&&[self.firstDieView showDie:roll];&&&&[self.secondDieView showDie:roll2];}
ViewController.m
This will take care of displaying the dice numbers on the screen.
Next we have to assign some text to the sumLabel UILabel.
Let’s construct an NSString representing the message we want to show:
12345678910
- (IBAction)rollButtonClicked:(id)sender{&&&&int roll = [self.model getDiceRoll];&&&&int roll2 = [self.model getDiceRoll];&&&&&&&&[self.firstDieView showDie:roll];&&&&[self.secondDieView showDie:roll2];&&&&&&&&NSString *sumText = [NSString stringWithFormat:@"Sum is %d", roll + roll2];}
ViewController.m
Above, we’re constructing a string with the sum of the two dice numbers we rolled.
Finally, let’s assign this string to the text property of the sumLabel IBOutlet property we created:
self.sumLabel.text = sumText;
Your “rollButtonClicked” method should look like this:
123456789101112
- (IBAction)rollButtonClicked:(id)sender {&&&&&int roll = [self.model getDiceRoll];&&&&int roll2 = [self.model getDiceRoll];&&&&&&&&[self.firstDieView showDie:roll];&&&&[self.secondDieView showDie:roll2];&&&&&&&&NSString *sumText = [NSString stringWithFormat:@"Sum is %d", roll + roll2];&&&&&&&&self.sumLabel.text = sumText;}
ViewController.m
Click the Run button in the upper left hand corner of XCode and the iOS Simulator will launch if you don’t have any errors.
If you have some errors, don’t worry! Read what the error says, look at the line of code it’s specifying and see if you can figure out what’s wrong.
It could be as simple as a typo. Re-read this article and follow the steps carefully and if you still fail to find the source of the error, download the source code below and compare your code with my code!
If you see the iOS Simulator come up and dice showing up when you click the Roll button…
Congratulations! You’ve just created a simple dice rolling application.
If that was your first iPhone application, then you’ve come a long way since Part 1!
In this part of the series, you’ve built an iPhone application from scratch!
Now you understand:
-Creating a data model
-Implementing a ViewController
-Creating a custom UIView
-Creating a user interface with Interface Builder
-Adding custom UIViews through Interface Builder
-Creating IBOutlets and IBActions
-Handling button clicks
-Implementing the MVC design pattern!
This concludes the end of my beginner series, How To Make iPhone Apps With No Programming Experience.
I hope that you’ve enjoyed it and that it’s inspired you to continue learning iOS development and building iOS apps.
If you’d like to take the next step in learning iOS development with me as your mentor and alongside over 260 other like-minded individuals, please consider joining my video course.
And lastly, if you know someone who wants to learn iPhone and iPad development, please share this article with them and help me reach more people!
Let’s improve this article together!
I want to make this series and this article in particular the best and easiest to understand resource for beginners to learn how to develop iPhone apps. If you’ve got any feedback, good or bad, please let me know via the comments below so I can update parts which are confusing, add more examples and to continue updating this resource.
And if you’ve enjoyed this article or you know someone who might be interested in learning how to build iOS apps, please share this series with them. It’s targeted at the non-programmer (sort of like an iPhone application development for dummies book) so anyone you know will be able to pick this up and progress towards developing iPhone apps!

我要回帖

更多关于 反问句改疑问句 的文章

 

随机推荐