Since the iPhone SDK was publicly released in March 2008, learning to program for the iPhone has become a very popular new skill. This tutorial demonstrates a simple example Utility application for the iPhone and iPod touch which allows the user to change the color of light that the program emits, acting as a simple flashlight. This tutorial is intended for someone who is starting to learn the iPhone SDK, but has completed the obligatory "Hello, World!" example and are prepared for a more advanced project.
To design an application for the iPhone or iPod touch, you will need Xcode 3.1 or later and an Intel-based Macintosh computer.
File > New Project
.iPhone OS
section, select a Utility Application
.Save
button.Since this is a Utility Application, Xcode has already generated several files and interface files (xib) for us. To maintain the simplicity of this project, we will not need to worry about the MainView
or FlipView .m
and .h
files.
Before we start coding, we'll set a couple of settings in the Info.plist
file to set the program's icon and its bundle identifier.
To add a little polish to this program, we'll need an application icon. What you'll need is a PNG file with a blank background that is no larger than 57x57 pixels in dimension. Your iPhone will automatically generate the glassy encapsulation effect for your icon. In this example, we have a simple image of a flashlight. With your icon, leave a few pixels of space around your icon so the edges don't get clipped.
Flashlight.png
.Add > Existing Files
. Navigate to your icon and add it to the project.Info.plist
file.Flashlight
.com.example.${PRODUCT_NAME:identifier}
, where example
would be your company name.Info.plist
. Single-click the row that says Information Property List
, and click the gray button at the end of the row to add a new row. Change the new row's Key to UIStatusBarHidden
. Next, right-click the empty Value column in the new row and select the Value Type
to be Boolean
in the context menu. In the new row a checkbox will appear. Click the checkbox so it is marked, which gives the value of YES or TRUE. Save your changes.The Main View has a simple set up. It is a full screen view that displays the set color and has a small Info icon in the bottom right corner to bring up the controls view.
Main View
folder to display the four "MainView" files (MainView.h, MainView.m, MainViewController.h, MainViewController.m
), and select the file MainViewController.h
.float
variables are used to read in the three color values from the preferences. The method updateBackgroundColor
is used to, not surprisingly, change the view's background color to the desired color. Your MainViewController.h
should look like the following:// // MainViewController.h // Taschenlampe // // Created by Chad Armstrong on 3/30/09. // Copyright Edenwaith 2009. All rights reserved. // #import <UIKit/UIKit.h> @interface MainViewController : UIViewController { float red; float green; float blue; } - (void) updateBackgroundColor; @end
viewdidLoad
method and add the following single line of code to this method [self updateBackgroundColor];
. Your method will look like the following: - (void)viewDidLoad { [self updateBackgroundColor]; }
- (void ) viewDidAppear: (BOOL) animated { [self updateBackgroundColor]; [super viewDidAppear: animated]; }
MainViewController
, we need to create the updateBackgroundColor
method which will read the values from the saved NSUserDefaults. If there isn't a saved value for one of the color variables, then it will be initially set with the value of 0.5. The first time this program launches, all three color values will be set to 0.5, which when combined, will create a medium gray background. Here's the code: - (void) updateBackgroundColor { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey: @"red"] != nil) { red = [defaults floatForKey: @"red"]; } else { red = 0.5; } if ([defaults objectForKey: @"green"] != nil) { green = [defaults floatForKey: @"green"]; } else { green = 0.5; } if ([defaults objectForKey: @"blue"] != nil) { blue = [defaults floatForKey: @"blue"]; } else { blue = 0.5; } self.view.backgroundColor = [UIColor colorWithRed: red green: green blue: blue alpha: 1.0f]; }
MainViewController.m
file. Now, open the MainView.xib interface file, stored in the Resources folder in Xcode.MainView
inside the MainView.xib window and then press ⌘-3 to bring up the Size Inspector panel.Add > Existing Files
and add the image Preview.png to your project. This image will be used in the Flipside View.FlipsideViewController.h
. We will need to add seven outlets for our interface items, three variables to contain the color values (red, green, blue
), and one new method declaration (changeColor:
). Three of the UILabels will need to be updated to display the current value of the sliders. The UIView colorView
will display a preview of the selected color.
// // FlipsideViewController.h // Taschenlampe // // Created by Chad Armstrong on 3/30/09. // Copyright Edenwaith 2009. All rights reserved. // #import <UIKit/UIKit.h> @interface FlipsideViewController : UIViewController { IBOutlet UILabel *redValue; IBOutlet UILabel *greenValue; IBOutlet UILabel *blueValue; IBOutlet UISlider *redSlider; IBOutlet UISlider *greenSlider; IBOutlet UISlider *blueSlider; IBOutlet UIView *colorView; float red; float green; float blue; } @property (nonatomic, retain) UILabel *redValue; @property (nonatomic, retain) UILabel *greenValue; @property (nonatomic, retain) UILabel *blueValue; @property (nonatomic, retain) UISlider *redSlider; @property (nonatomic, retain) UISlider *greenSlider; @property (nonatomic, retain) UISlider *blueSlider; @property (nonatomic, retain) UIView *colorView; - (IBAction) changeColor: (id) sender; @end
Flipside View
in the FlipsideView.xib window and open the Size Inspector (⌘-3) and change the height from 460 to 480.red, green, blue
). The last UILabel will display the value of the slider.Image
to Preview.png
.redSlider, greenSlider, blueSlider
), the three UIViews which display the sliders' values (redValue, greenValue, blueValue
), and one connection to the UIView colorView
. You will perform this seven times to connect up each of the seven IBOutlets.Tag
to these values: redSlider: 0, greenSlider: 1, blueSlider: 2. These tags are set to identify each of the sliders when they are sending an event notification to the changeColor:
method, which helps reduce the amount of code needed.Value Changed
. Control-click and drag from the circle to the right of Value Changed
over to File's Owner. A context menu will appear over File's Owner -- select changeColor:
. Repeat this process with the other two sliders. Whenever one of the sliders is changed, an event will be called, announcing that one of the values is changing.FlipsideViewController.m
for some more coding.@synthesize
lines near the beginning of your code for each of your seven IBOutlets
.@synthesize redValue;
viewDidLoad
, we will perform similar steps to what we wrote in MainViewController.m
's updateBackgroundColor
method by loading in the current saved preferences (if they exist) and loading them into the program. After the three values for red, green, and blue
have been read in and assigned to the local float
variables, set the values for the three UILabels (redValue, greenValue, blueValue
), set the position for the three sliders, and set the color for the UIView colorView
.
- (void)viewDidLoad { self.view.backgroundColor = [UIColor whiteColor]; // set background color to white // Load up defaults NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey: @"red"] != nil) { red = [defaults floatForKey: @"red"]; } else { red = 0.5; } if ([defaults objectForKey: @"green"] != nil) { green = [defaults floatForKey: @"green"]; } else { green = 0.5; } if ([defaults objectForKey: @"blue"] != nil) { blue = [defaults floatForKey: @"blue"]; } else { blue = 0.5; } redValue.text = [NSString stringWithFormat: @"%1.2f", red]; greenValue.text = [NSString stringWithFormat: @"%1.2f", green]; blueValue.text = [NSString stringWithFormat: @"%1.2f", blue]; redSlider.value = red; greenSlider.value = green; blueSlider.value = blue; colorView.backgroundColor = [UIColor colorWithRed: red green: green blue: blue alpha: 1.0f]; }
viewWillDisappear
method is used to save the red, green
, and blue
settings back to the preferences when the Flip View disappears, which occurs when the Done button is pressed and the Main View is loaded.
- (void) viewWillDisappear: (BOOL) animated { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setFloat: red forKey: @"red"]; [defaults setFloat: green forKey: @"green"]; [defaults setFloat: blue forKey: @"blue"]; [super viewWillDisappear: animated]; }
changeColor
method is where the real work is performed to change the color.
Since all three of the UISliders call this method, we first grab the value of the sending UISlider and put that value into the float
variable sliderValue
. Next, we check which UISlider is the originating sender by looking at the tag
. You did remember to set the tags for each of the UISliders in Interface Builder, right? The redSlider
has a value of 0, greenSlider
is 1, and the blueSlider
is 2. Once the appropriate value has been updated, the colorView
's background color is updated to reflect the new color. When the Main View is brought up again, it will display this new color.
- (IBAction) changeColor: (id) sender { UISlider *slider = (UISlider *)sender; float sliderValue = (float)slider.value; if ([sender tag] == 0) // red { redValue.text = [NSString stringWithFormat: @"%1.2f", sliderValue]; red = sliderValue; } else if ([sender tag] == 1) // green { greenValue.text = [NSString stringWithFormat: @"%1.2f", sliderValue]; green = sliderValue; } else if ([sender tag] == 2) // blue { blueValue.text = [NSString stringWithFormat: @"%1.2f", sliderValue]; blue = sliderValue; } colorView.backgroundColor = [UIColor colorWithRed: red green: green blue: blue alpha: 1.0f]; }
dealloc
method deallocates the memory taken for the seven IBOutlets we are using in this view.
- (void)dealloc { [redValue dealloc]; [greenValue dealloc]; [blueValue dealloc]; [redSlider dealloc]; [greenSlider dealloc]; [blueSlider dealloc]; [colorView dealloc]; [super dealloc]; }
By this point, everything should be set up and ready to go. Compile your program, and if it is successful, the iPhone Simulator will launch, displaying the iPhone program. Click on the small "i" in the bottom-right corner to switch to the flip view. The flip view then displays the various controls which you can manipulate. When you have selected a color, press the Done button. If you press the simulator's Home button and then launch the program again, you will notice that the last color is still available.
If you are experiencing problems with your project, look through the source files or the entire project which are included below.