Basic iPhone UI Elements

Basic iPhone UI Elements

by Paul Avery

Introduction

Since this is the first iPhone article published on CodeGuru, I thought it best to start from the very beginning. This article will address the creation of a new project from scratch and interaction with the following basic iPhone UI elements.

  • UIView
  • UILabel
  • UITextField
  • UIButton
  • UIAlertView

However, in order to proceed any further, there is a basic level of understanding needed of Cocoa Touch. It is primarily Objective-C, which is C with an object-oriented flavor. It's syntax can either be bracket based or dot based. Dot syntax was added with Objective-C 2.0 and will be more familiar to those coming from a .NET background. For the most part, I will stick with the dot syntax.

If you know absolutely nothing about about anything C based, I highly suggest you visit http://cocoadevcentral.com/d/learn_objectivec/ before proceeding any further.

  // bracket syntax
  [imgView setImage:myImage];
  // dot syntax
  imgView.image = myImage;

 

Creating a New Project

Apple is very big on "out of the box" solutions. Using Xcode and Interface Builder is no exception. When starting a project from scratch, most options will automatically add the main UIWindow and primary UIView element for you.

So, let's begin. Start by selecting "New Project..." from the "File" menu. You will see a dialog like the following image. Select "View-based Application" and click "Choose..." After that, you will be allowed to name your project. For simplicity sake, I named mine "Basic."

Now, you should have your created project with 2 main class files: BasicAppDelegate.h/m and BasicViewController.h/m. Your project should also include 3 main resource files: MainWindow.xib, BasicViewController.xib, and Basic-Info.plist. There are other files in your project, but we will concentrate on just these 5 for now. Files with a .h/m extension are classes, .xib are interfaces, and .plist are property lists.

BasicAppDelegate.h/m is the first class referenced. It controls the MainWindow.xib interface and subclasses the primary view controller. BasicViewController.h/m controls BasicViewController.xib which is the primary view that is displayed. This class will be where we focus our attention for majority of this project.

Property List

Before proceeding any further, we need to change some settings in the Basic-Info.plist property list. Typically, you will want to have the Bundle identifier include your company name. Also, remember that version incrementing and icons are controlled using this file. However, those aren't the only settings this property list handles.

Basic iPhone UI Elements

Working with the UI Elements

Now that all of the introductory project creation work is complete, we can finally start attaching visual UI elements to our view. Even though we didn't create a new UIView, the project did that for us...BasicViewController.h/m. So, open the .h file, and let's get started with some code.

The .h file extension stands for header. In this file we will need to declare one UITextField to be retained in memory and one custom method for the tapping of a UIButton. We also need to make sure that this class supports the delegate methods for the UITextField. So, in order to do that, we simply declare it in the interface line.

#import <UIKit/UIKit.h>

@interface BasicViewController : UIViewController <UITextFieldDelegate> {
	UITextField *txtName;
}

@property (nonatomic, retain) UITextField *txtName;

- (void)sayHello:(id)sender;

@end

 

Now that the header file is done, let's take a look at the .m file. It stands for implementation. This is where we will put all methods and references to created objects. First off, in the viewDidLoad method, we want to customize the current view. We're going to give it a simple white background color.

- (void)viewDidLoad {
	// change the view's background to white
	self.view.backgroundColor = [UIColor whiteColor];

	...

	[super viewDidLoad];
}

 

Second, we want to attach a UILabel. The UILabel is one of the easiest elements to work with in iPhone development. It gives the developer a simple method for letting the app user know some bit of information in the form of text. For this one, we will just ask the person's name.

- (void)viewDidLoad {
	// change the view's background to white
	self.view.backgroundColor = [UIColor whiteColor];

	// create the UILabel
	// the parameters for CGRectMake are x, y, width, height
	UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 24.0)];
	lblName.font = [UIFont systemFontOfSize:14];
	lblName.textColor = [UIColor blackColor];
	lblName.textAlignment = UITextAlignmentLeft;
	lblName.text = @"What is your name?";
	// attach the UILabel to the view
	[self.view addSubview:lblName];
	// release the UILabel from memory allocation
	[lblName release];

	...

	[super viewDidLoad];
}

 

Third, we would like some user feedback. A very common method for doing so is to use a UITextField. This allows for users to input text for later use.

- (void)viewDidLoad {
	// change the view's background to white
	self.view.backgroundColor = [UIColor whiteColor];

	// create the UILabel
	// the parameters for CGRectMake are x, y, width, height
	UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 24.0)];
	lblName.font = [UIFont systemFontOfSize:14];
	lblName.textColor = [UIColor blackColor];
	lblName.textAlignment = UITextAlignmentLeft;
	lblName.text = @"What is your name?";
	// attach the UILabel to the view
	[self.view addSubview:lblName];
	// release the UILabel from memory allocation
	[lblName release];

	// create the UITextField
	UITextField *tmptxtName = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 44.0, 300.0, 32.0)];
	tmptxtName.borderStyle = UITextBorderStyleRoundedRect;
	tmptxtName.font = [UIFont systemFontOfSize:24];
	tmptxtName.adjustsFontSizeToFitWidth = YES;
	tmptxtName.textColor = [UIColor blackColor];
	tmptxtName.backgroundColor = [UIColor whiteColor];
	// placeholder is the text shown when the UITextField is blank
	// it is shown in a light gray
	tmptxtName.placeholder = @"John Doe";
	tmptxtName.clearsOnBeginEditing = YES;
	// the next 4 lines refer to the UITextFieldDelegate properties
	tmptxtName.keyboardType = UIKeyboardTypeDefault;
	tmptxtName.returnKeyType = UIReturnKeyDone;
	tmptxtName.autocorrectionType = UITextAutocorrectionTypeNo;
	tmptxtName.delegate = self;
	// make the keyboard show right away
	[tmptxtName becomeFirstResponder];
	// attach the UITextField to the view
	[self.view addSubview:tmptxtName];
	// in the header file we needed to retain a textfield in the memory for later use
	// this is setting the class' UITextField object to this newly created object
	self.txtName = tmptxtName;
	// release the temporary UITextField from memory allocation
	[tmptxtName release];

	...

	[super viewDidLoad];
}

 

Lastly, in the viewDidLoad method, we are going to add a UIButton. When the user finishes inputting his/her name, he/she can tap the button to see the result.

- (void)viewDidLoad {
	// change the view's background to white
	self.view.backgroundColor = [UIColor whiteColor];

	// create the UILabel
	// the parameters for CGRectMake are x, y, width, height
	UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 24.0)];
	lblName.font = [UIFont systemFontOfSize:14];
	lblName.textColor = [UIColor blackColor];
	lblName.textAlignment = UITextAlignmentLeft;
	lblName.text = @"What is your name?";
	// attach the UILabel to the view
	[self.view addSubview:lblName];
	// release the UILabel from memory allocation
	[lblName release];

	// create the UITextField
	UITextField *tmptxtName = [[UITextField alloc] initWithFrame:CGRectMake(10.0, 44.0, 300.0, 32.0)];
	tmptxtName.borderStyle = UITextBorderStyleRoundedRect;
	tmptxtName.font = [UIFont systemFontOfSize:24];
	tmptxtName.adjustsFontSizeToFitWidth = YES;
	tmptxtName.textColor = [UIColor blackColor];
	tmptxtName.backgroundColor = [UIColor whiteColor];
	// placeholder is the text shown when the UITextField is blank
	// it is shown in a light gray
	tmptxtName.placeholder = @"John Doe";
	tmptxtName.clearsOnBeginEditing = YES;
	// the next 4 lines refer to the UITextFieldDelegate properties
	tmptxtName.keyboardType = UIKeyboardTypeDefault;
	tmptxtName.returnKeyType = UIReturnKeyDone;
	tmptxtName.autocorrectionType = UITextAutocorrectionTypeNo;
	tmptxtName.delegate = self;
	// make the keyboard show right away
	[tmptxtName becomeFirstResponder];
	// attach the UITextField to the view
	[self.view addSubview:tmptxtName];
	// in the header file we needed to retain a textfield in the memory for later use
	// this is setting the class' UITextField object to this newly created object
	self.txtName = tmptxtName;
	// release the temporary UITextField from memory allocation
	[tmptxtName release];

	// create the UIButton
	UIButton *btnOK = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	btnOK.frame = CGRectMake(110.0, 92.0, 100.0, 32.0);
	[btnOK setTitle:@"Say Hello" forState:UIControlStateNormal];
	[btnOK setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	btnOK.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	btnOK.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	// attach the custom sayHello method to the tapping of this button
	[btnOK addTarget:self action:@selector(sayHello:) forControlEvents:UIControlEventTouchUpInside];	
	[self.view addSubview:btnOK];
	// notice that the UIButton was not allocated to memory at it's creation
	// therefore we do not need to release it

	[super viewDidLoad];
}

 

Basic iPhone UI Elements

Now, since the keyboard has a "Done" button, we want that to also trigger the message. So, the user can either tap the "OK" button, or tap the "Done" button on the keyboard. This is where we need the delegate method for the UITextField.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[self sayHello:nil];
	return YES;
}

 

Finally, to finish up the project, we need to create the custom method for displaying the message to the user. For this method, we will be displaying a UIAlertView and then dismissing the keyboard.

- (void)sayHello:(id)sender {
	// display a hello alert
	NSString *title = [NSString stringWithFormat:@"Hello %@!", self.txtName.text];
	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:nil message:title delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
	[myAlert show];
	[myAlert release];

	// dismiss the keyboard
	[self.txtName resignFirstResponder];
}

 

Just one line more and we're done. Remember how we retained a UITextField in the class' header file? Now we need to release that if the class deallocates from memory. In the class' dealloc method, we release the class' retained object.

- (void)dealloc {
	// release the class' UITextField from memory if the class is deallocated
	[self.txtName release];
	[super dealloc];
}

 

Done!

That's it. You should be able to build and run the project using either a testing device or the iPhone Simulator.

[screenshot.png]


About the Author

Paul Avery

www.peejstudio.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date