Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Tutorials

Reply
 
LinkBack Thread Tools Display Modes
Old 08-18-2011, 01:29 PM   #1 (permalink)
Registered iOS Developer
 
Join Date: Jul 2011
Posts: 110
studentlost is on a distinguished road
Post Gas Cost Splitter Tutorial

Part I. (Creating the utility project and setting up the main view interface that will be viewed by the application user.)

To start, open up the latest stable version of Xcode and create a new Utility project. You'll want to create it for the iPhone. Give it whatever name you like.

This project will contain two views, a main view, and a flip view. Currently, the main view nib* file is called MainView, and the flip view nib is called FlipView. This may change in later versions of Xcode. You will also see a MainWindow nib file. You can ignore this.

*Nib files are also referred to as XIB files. The latest version of Xcode will have your interface files ending with the extension .xib. This are the same as .nib files.

Open up the MainView XIB file. In the main view, add these 5 labels: Miles Per Gallon, Distance to travel (miles), Price per Gallon (in dollars), # of Passengers, and finally, Total Owed by Each (in dollars).

You'll want to add a textfield next to each of these labels, which will correspond to the label it represents.

Finally, add a button and title it "Calculate". Save your XIB file and go back to your project. We'll be coming back to this XIB file later to connect the outlets and actions.


Part II. (Creating an NSObject class for the Calculator portion of the code, as well as an NSObject class for the CalculatorController.)

In your project, right click on your project and select "Add File", or press Command and N. You want to add a new Objective C Class. Make it a subclass of NSObject. Name this class "Calculator".


This is what your .h should look like for Calculator.

Calculator.h
Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

#import Foundation/Foundation.h> //Imports Foundation Framework of the Objective C Class. //

@interface Calculator : NSObject {
    //Creating the float variables for mpg, miles, riders, price, and split. //
	float mpg, miles, riders,price, split;
}
//Declaring the property of float variables from interface above. //
@property(readwrite) float mpg, miles, price, riders;

//Float method for the calculation. //
- (float) CalculateSplit;

@end
This is what your .m should look like for Calculator.

Calculator.m
Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

#import "Calculator.h"

@implementation Calculator

//Synthesizes float variables declared in the .h file for complete implementation. //
@synthesize mpg, miles, price, riders;

//Calculation method to determine the amount owed by each passenger. //
- (float)CalculateSplit {
	return ((self.miles)*(self.price)) / ((self.mpg) * (self.riders));
}

@end

Now, add another Objective C Class with a subclass of NSObject. Call this class, "CalculatorController".

This is what your .h should look like for CalculatorController.

CalculatorController.h
Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

#import Foundation/Foundation.h> //Imports Foundation Framework of the Objective C Class. //

@class Calculator;

@interface CalculatorController: NSObject{
    
    //Declares the pointer for the Calculator. //
	Calculator *calculator;
    
}

//Float method that is calculated by sending mpgField...ridersField from the textfield to the calculator. //
-(float)calculator:(NSString *)mpgField : (NSString *)milesField : (NSString *)priceField : (NSString *)ridersField;

@end
This is what your .m should look like for CalculatorController.

CalculatorController.m
Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

#import "PriceCalculatorController.h"

//Imports Calculator. //
#import "Calculator.h"

@implementation CalculatorController

//Defines the float method for pointing the data entered in the textfield to the calculator. //
-(float)calculator:(NSString *)mpg : (NSString *)miles : (NSString *)price : (NSString *)riders
{
    //Allocates the Calculator to calculator. //
    calculator = [[Calculator alloc]init];
    //Connects the float variables to the textfied variables from the interface. //
	[calculator setMpg:[mpg floatValue]];
	[calculator setRiders: [riders floatValue]];
    [calculator setMiles: [miles floatValue]];
    [calculator setPrice: [price floatValue]];
    //Assigns split the float value that results from the calculator. //
    float split = [calculator CalculateSplit];
	return (split);
}
@end

Part III. (Editing the MainViewController .h and .m files, adding all outlets and actions as well as methods needed to create a functional application.)


First, go to the MainViewController.h file and add this piece of code to the top.

Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

//Import CalculatorController into the MainViewController. //
#import "CalculatorController.h"
Now, in the interface declaration between brackets, you want to add the UIButton and UITextfields that your application interface will be interacting with.

Here is what the interface declaration code will look like.

Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

@interface MainViewController : UIViewController  
{
    //Setting up the calculator button. //
    UIButton					*calculatorButton;
    //Setting up the text field for mpg, miles, price of gas, passengers, and the total owed by each. //
    UITextField					*mpgField;
	UITextField					*milesField;
	UITextField					*priceField;
	UITextField					*ridersField;
	UITextField					*splitField;
    //Setting up the CalculatorController pointer. //
	CalculatorController	*calcController;
}
Next, add this portion of code to the rest of your MainViewController header file.

Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

//Declaring all properties that were set up in the MainViewController interface above. //

@property (nonatomic, retain) IBOutlet UIButton	*calculatorButton;
@property (nonatomic, retain) IBOutlet UITextField	*mpgField;
@property (nonatomic, retain) IBOutlet UITextField	*milesField;
@property (nonatomic, retain) IBOutlet UITextField	*priceField;
@property (nonatomic, retain) IBOutlet UITextField	*ridersField;
@property (nonatomic, retain) IBOutlet UITextField	*splitField;

//Creates the action of clicking the show info button in the interface. //
-(IBAction)showInfo:(id)sender;

//Creates the action of clicking the calculator button in the interface. //
-(IBAction)calculatorButtonClicked:(id)sender;
You are done setting up your MainViewController.h file.


Next, go to the MainViewController.m file.

You first will want to synthesize your variables declared in the MainViewController.h file.

Add this portion of code after implementation.

Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

//All properties that were defined in the .h file are being synthesized here for complete implementation. //
@synthesize calculatorButton;
@synthesize mpgField;
@synthesize milesField;
@synthesize priceField;
@synthesize ridersField;
@synthesize splitField;
The last part of code you need to add to the MainViewController.m file is the action method when the calculator button in the user interface is pressed.


Add this code snippet to your MainViewController.m file.

Code:
// Copyright(c) 2011. Not for distribution, commercial or otherwise. //

// The calculator button has been selected. //
-(IBAction)calculatorButtonClicked:(id)sender
{
    //Allocates PriceCalculator Controller. //
    calcController = [[CalculatorController alloc] init];
	//Assigns the calculation to the float variable, fSplit. mpgField.text... ridersField.text are the variables with data needed in order to complete the calculation. They are pulled from the textfields in the interface. //
	float fSplit = [calcController calculator:mpgField.text : milesField.text : priceField.text : ridersField.text];
    //Here, splitField is being assigned the value of fSplit. splitField is what appears in the interface textfield that represents the total amount of money owed by each person. %.2f in the string format means that the float will be rounded to two decimals, because it's in dollars. //
	[splitField setText:[NSString stringWithFormat:@"%.2f", fSplit]];
    //The calcCantroller is released. //
    [calcController release];
}
Part IV. (Connecting the outlets and actions in the Main view interface, and building and running the finished application.)

Now go back to your MainView XIB file.

You want to click on file owner, and select, Show Connections Inspector.

Under outlets, connect each field to its appropriate textfield on the interface. For example, mpgField goes to the textfield where users will be entering their car's average miles per gallon, and so on. Make sure you connect each outlet to its proper textfield, otherwise your calculations will be wrong.

Finally, under received actions in the Show Connections Inspector, connect the calculatorButtonClicked action to the Calculate button, and select "Touch up inside".

Save and exit. Now, you can build and run your project in the simulator. Hopefully, it builds without any issues and you've got the app running.

Please feel free to leave any feedback or ask any questions that may come up.

I hope this was beneficial to you!



Copyright(c) 2011. Only For Educational Reference. Not for distribution, commercial or otherwise.

Last edited by studentlost; 08-20-2011 at 03:13 PM.
studentlost is offline   Reply With Quote
Old 08-18-2011, 07:36 PM   #2 (permalink)
Registered iOS Developer
 
Join Date: Jul 2011
Posts: 110
studentlost is on a distinguished road
Smile

This tutorial covers the basic concepts of receiving input from the user through a text field, taking this input received, using it to calculate a result, and then finally adding this result into a textfield to be displayed in the application interface.

I've inserted comments on almost every line that talk about what each portion of code represents and its importance.

A very special thanks to MattW of FourSixteen Productions for his help and support.


Feel free to use this tutorial as a reference guide in creating your own applications, but please do not copy and paste it and try to distribute it as such. It was created to help benefit the community, not to give you the opportunity to become second handers.
Thank you!

Last edited by studentlost; 08-19-2011 at 12:39 AM.
studentlost is offline   Reply With Quote
Reply

Bookmarks

Tags
calculation, ibaction, methods, textfield, tutorial

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 468
13 members and 455 guests
alexeir, David-T, Dj_kades, foslock, iAppDeveloper, jeroenkeij, LunarMoon, Mijator, pipposanta, QuantumDoja, robsmy, sacha1996, usernametaken
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,679
Threads: 94,129
Posts: 402,928
Top Poster: BrianSlick (7,990)
Welcome to our newest member, xzoonxoom
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 09:25 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0