Taschenlampe - iPhone Tutorial

Written by: Chad Armstrong
Created: 9 April 2009
Last modified: 21 April 2009

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.

Get the appropriate tools

To design an application for the iPhone or iPod touch, you will need Xcode 3.1 or later and an Intel-based Macintosh computer.

Create a new project
  1. Start up Xcode and select File > New Project.
  2. Under the iPhone OS section, select a Utility Application.
  3. Give the project a name and click the 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.

Add icon

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.

  1. Create an icon for your program. For this example, we have the image Flashlight.png.
  2. Right-click on your Resources folder in Xcode's Groups and Files pane. Select Add > Existing Files. Navigate to your icon and add it to the project.
  3. Expand the Resources folder and click on the Info.plist file.
  4. Set Icon's value to the icon name. In this example, the value would be Flashlight.
  5. Next, set the Bundle Identifier name for your project, which follows the form of com.example.${PRODUCT_NAME:identifier}, where example would be your company name.
  6. We will want to make this a full-screen application, so we will need to add an extra value to the 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.
Setting up the Main View

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.

  1. Expand the Main View folder to display the four "MainView" files (MainView.h, MainView.m, MainViewController.h, MainViewController.m), and select the file MainViewController.h.
  2. We will only need to add three instance variables and one method declaration. The three 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
    					
  3. Uncomment the 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];
    }					
    						
  4. Next, add the following code, which gets loaded each time the Main View appears. This is important, since when the Main View is shown (at program launch, or when the flip side view is hidden), it will read the updated preference file and update the background color.
    - (void ) viewDidAppear: (BOOL) animated
    {
    	[self updateBackgroundColor];
    	[super viewDidAppear: animated];
    }
    						
  5. To finish off the coding for 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];
    }					
    						
  6. That's all the work we need to do on the MainViewController.m file. Now, open the MainView.xib interface file, stored in the Resources folder in Xcode.
  7. Select MainView inside the MainView.xib window and then press ⌘-3 to bring up the Size Inspector panel.
  8. In the Size Inspector panel, change the height from 460 to 480. This will make the view take up the entire iPhone screen. Save the file. That's all the work necessary for the Main View.
Setting Up the Flip View

  1. Now it is time to set up the interface file. First, right-click on the Resources folder and select Add > Existing Files and add the image Preview.png to your project. This image will be used in the Flipside View.
  2. Open the file 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
    						
  3. Now that we have the header file complete, open up FlipsideView.xib in Interface Builder. Same as what we did with the Main View, select Flipside View in the FlipsideView.xib window and open the Size Inspector (⌘-3) and change the height from 460 to 480.
  4. We will need to add eleven objects to our Flipside View: six UILabels, three UISliders, one UIImageView, and one UIView.
  5. We will start out by setting up three rows, where each row will contain a UILable, a UISlider, and then another UILabel. The first UILabel is merely a descriptive field that will display a color name (Red, Green, or Blue). The slider will be used to change the value of the corresponding color variable (red, green, blue). The last UILabel will display the value of the slider.
  6. Next, align the UIImageView and the UIView below the labels and sliders. Select the UIImageView and press ⌘-1. In the Attributes Inspector, change the value of Image to Preview.png.
  7. Time to set up some connections in Interface Builder. Control-click and drag from File's Owner in the Flipside View.xib window and connect the File's Owner to the three UISliders (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.
  8. Press ⌘-1 to open up the Attributes Inspector. Cycle through each of the three sliders again, and set the 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.
  9. Select one of the sliders and open up the Connections Inspector by pressing ⌘-2. Expand the Events section, if necessary, and find the event 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.
  10. That's all for Interface Builder. Switch over to FlipsideViewController.m for some more coding.
  11. Since we are using Objective-C 2, add the seven @synthesize lines near the beginning of your code for each of your seven IBOutlets.
    Example: @synthesize redValue;
  12. In 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];
    }
    						
  13. The 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];
    }
    						
  14. The new 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];
    }
    						
  15. The 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];
    }
    						
Compiling and Testing

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.

Reference files