Xcode 4 Cookbook - Packt Publishing | Technology Books ... · a detailed guide for using the...

40
Xcode 4 Cookbook Steven F. Daniel Chapter No. 2 "User Interfaces – Creating the UI"

Transcript of Xcode 4 Cookbook - Packt Publishing | Technology Books ... · a detailed guide for using the...

Xcode 4 Cookbook

Steven F. Daniel

Chapter No. 2 "User Interfaces – Creating the UI"

In this package, you will find: A Biography of the author of the book

A preview chapter from the book, Chapter NO.2 "User Interfaces – Creating the UI"

A synopsis of the book’s content

Information on where to buy this book

About the Author Steven F. Daniel is originally from London, England, but lives in Australia.

He is the owner and founder of GENIESOFT STUDIOS (http://www.geniesoftstudios. com/), a software development company based in Melbourne, Victoria, that currently develops games and business applications for the iOS, Android, and Windows platforms.

Steven is an experienced software developer with more than 13 years of experience developing desktop and web-based applications for a number of companies including, insurance, banking and finance, oil and gas, and local and state government.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Steven is always interested in emerging technologies, and is a member of the SQL Server Special Interest Group (SQLSIG) and the Java Community. He has been the co-founder and Chief Technology Officer (CTO) of SoftMpire Pty Ltd., a company that focused primarily on developing business applications for the iOS and Android platforms.

He is the author of Xcode 4 iOS Development Beginner's Guide, iOS 5 Essentials, and iPad Enterprise Application Development Blueprints.

You can check out his blog at http://geniesoftstudios.com/blog/, or follow him on twitter at http://twitter.com/GenieSoftStudio.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Xcode 4 Cookbook The Xcode 4 Cookbook provides you with the skills and knowledge, and practical recipes on how to go about developing useful applications that can be used within the industry. By using this cookbook's step-by-step style approach, presenting examples in the style of recipes, allowing you to go directly to your topic of interest, or follow topics throughout a chapter to gain in-depth knowledge, you will gain the skills needed to develop some stunning applications.

This cookbook is a practical guide featuring over 100 recipes that show you how to build your own fun and exciting iOS applications by integrating iCloud, Facebook, Mobile core services, Core Image and Media Player Frameworks, and the Core Graphics and Core Motion frameworks, that will enable you to enhance your applications to create some amazing image and transition effects using the built-in image filters.

In this book, I have tried my best to keep the code simple and easy to understand. I have provided step-by-step instructions with loads of screenshots at each step to make it easier to follow. You will soon be mastering the different aspects of iOS 6 programming, as well as mastering the technology and skills needed t o create some stunning applications.

Feel free to contact me at [email protected] for any queries, or if you just want to drop by and say "Hello". Any suggestions for improving this book will be highly regarded.

What This Book Covers Chapter 1, Getting and Installing the iOS SDK Development Tools, introduces the developer to the Xcode developer set of tools, as well as the capabilities of the iOS Simulator and each of the layers contained within the iOS architecture, before finally looking at how to create a simple Hello World iOS application.

Chapter 2, User Interfaces – Creating the UI, introduces the concept of views and how they are part of a complete iOS application. Exploring a large number of various view components, you will create different applications that will help you understand how each component works. We will also learn about the Model View Controller (MVC) pattern and how to use it to create applications suitable for enhanced user experience. Through this chapter, you will also learn about the most useful controllers, which will be part of many of your projects in the future.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 3, Using Storyboards, gains an understanding of what Storyboards are and how we can apply the various transitions between views. We will take a look into how we are able to create and configure scenes and storyboard files, to present these programmatically. Finally, we will learn how to integrate Twitter capabilities into our application to tweet photos and standard messages using the new iOS 6 Social frameworks.

Chapter 4, Using Xcode Instruments, focuses on how to effectively use Instruments within our applications to track down memory leaks and eliminate bottlenecks that could potentially cause our application to crash on the user's iOS device. We will also take a look at how to add and configure instruments, as well as learn how to use the System Trace Instrument to monitor system calls and track down performance issues within the application.

Chapter 5, Working with the Location Services and the MapKit Frameworks, introduces a detailed guide for using the built-in location services to create applications that provide location information to the user. You will not only learn how to use the GPS hardware, but also how to display maps and layout information using Overlays.

Chapter 6, Storing Documents within the Cloud, introduces you to the benefits of using iCloud, and how to incorporate iCloud functionality into your applications to store and retrieve files, and its data through the use of the Storage APIs. This chapter will also give you some insight into how to go about handling file version conflicts when multiple copies of the same file are being updated on more than one iOS device.

Chapter 7, Working with the Different Multimedia Resources, focuses on teaching you to create applications that capture, reproduce, and manage multimedia content through the device's hardware. You will not only learn to use the camera to capture images and videos but also how to play back and record audio. We will also learn how to implement the different image filter effects and transition animations to produce a water ripple effect, as well as learning how to incorporate Airplay functionality into our application.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 8, Working with the CoreData and GameKit Frameworks, focuses on showing you how to use the Core Data framework to create a simple Books Library application, to directly interface with a SQLite database, to create and store book details. We will also look at how to incorporate Bluetooth functionality, so that you can send book details to another iOS device, and have this information received wirelessly and stored within the database at the other end.

Chapter 9, Creating a Social Networking App with the Facebook iOS SDK, shows you how to download the Facebook SDK and register your application with Facebook. It also shows you how to use the Facebook APIs to integrate Facebook functionality into your app, using the Single Sign On (SSO) feature. This provides users the ability to sign into your application using their Facebook identity, so that they can submit notification requests, or submit content to their wall. We will learn how to use the Open Graph API and Facebook Query Language (FQL) to pass SQL Query like syntax to retrieve information about the current user, and learn how to cleanly handle Facebook errors within our iOS applications.

Chapter 10, Packaging and Deploying Your Application, walks you through the required steps to deploy your finished application to devices, as well as showing you how to prepare and distribute it to the App Store. We will also take a look at how to create and obtain provisioning profiles for both development and distribution.

Appendix, Exploring the MultiTouch Interface, discusses how to create applications that are fully aware of their surrounding environment, through the device's sensors. You will learn to adjust the user interface according to device orientations and how to respond to accelerometer and gyroscope events. You will also learn about the built-in shake gesture, and how to go about responding to the shake motions.

For More Information: www.packtpub.com/xcode-4-cookbook/book

2User Interfaces –

Creating the UI

In this chapter, we will cover:

Adding and customizing views

Using labels to display text

Obtaining user input through the use of buttons

Displaying an image within the view

Displaying and editing text

Using the iOS device keyboard

Displaying the progress to the user

Adding a toolbar object to a view

Fading a view in and out

Creating a custom table view controller

Adding a table view to a view controller

Handling different iOS devices

IntroductionAn application's user interface which is comprised of views and other elements, is the fi rst thing the user sees when he/she loads up your application and provides him/her with an easy way of communicating with your application.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

46

The user interface consists of a canvas, and acts as a placeholder for your controls that the user can communicate with. In most real-world applications, views alone are simply not enough. Apple provides you with another class called UIViewController, which is responsible for managing views.

View controllers can respond to device notifi cations, such as determining when the device rotates, or can provide you with different ways of displaying and dismissing multiple views or even other view controllers.

We will also see how to use some of the most common view controllers to create our own custom classes. In this chapter, we will look at how we can add and customize views, as well as apply transitions to these to have them fade in and out. We will also take a look at some of the device specifi c aspects of the device, to determine its current orientation.

Adding and customizing viewsIn this recipe, we will look at how we can add a new UIView object to our existing view using Interface Builder and take a look at how we can customize this.

Getting readyWe will start by creating a new project using Xcode, and then use Interface Builder to help us add a new UIView object, so let's get started.

How to do it...To begin with creating a new Xcode project, perform the following simple steps:

1. Launch Xcode from the /Developer/Applications folder.

2. Select Create a new Xcode project, or click on File | New Project.

3. Select Single View Application from the list of available templates.

4. Click on the Next button to proceed to the next step in the wizard.

5. Next, enter ViewObjectsExample as the name for your project.

6. Select iPhone from under the Devices drop-down menu.

7. Ensure that the Use Storyboards checkbox has not been checked.

8. Ensure that the Use Automatic Reference Counting checkbox has been checked.

9. Ensure that the Include Unit Tests checkbox has not been checked.

10. Click on the Next button to proceed to the next step in the wizard.

11. Specify the location where you would like to save your project.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

47

12. Then, click on the Create button to save your project at the specifi ed location.

Once your project has been created, you will be presented with the Xcode development environment along with the project fi les that the template created for you.

Next, we need to start building our user interface, which can be achieved by performing the following simple steps:

1. Select the ViewController.xib fi le from the project navigator window.

2. From Object Library, drag a View object onto the main view.

3. Next, create the necessary outlet and property for this view, and name it subView.

4. Next, select the new view that we just added and from the Size Inspector tab, set the Y property to 44 points, the Width property to 320 Points, and the Height property to 480 points.

5. Next, save your project by selecting File | Save, or alternatively by pressing command + S.

6. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear with your application that we just created and displayed showing a view with a white background.

How it works…We just created an application that consists of a subview, which does not provide any functionality. In iOS applications, views are one of the important components that make up an application's user interface that inherits from the UIView class hierarchy.

It is worth mentioning what happens when a view is added using Interface Builder as opposed to having this dynamically created through code, which we will shortly take a look at. Views added using Interface Builder are instantiated at runtime and set the Frame property using the values that have been set manually in the Size Inspector window. The Frame property is of type CGRect and this defi nes the location of the view in the main window, as well as its size in points.

There's more…The UIView class inherits from the UIResponder class that is responsible for responding to and handling events. When a view is added to an existing view, it becomes part of its responder chain. The UIView class exposes the properties and the associated methods of the UIResponder class.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

48

If you would like to fi nd more information on the UIResponder class, you can refer to the Apple Developer documentation located at http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/cl/UIResponder.

Views can also be added programmatically through code using the addSubView method of the UIView class. The following line of code shows you how this can be achieved:

[self.view addSubview:self.subView];

As you can see from the preceding line of code snippet, the addSubview method sets the added view's Superview object to point to the caller. A view will not be displayed until it has been added to the main parent view using the addSubview method. Adding the same view to another view will result in the Superview object to change and point to the new view's parent window. This is because a view can only exist in one Superview object at any given time.

It is worth noting that when adding views manually using Interface Builder, you don't need to use the addSubview: method to display the subview, depending on whether you have already added it as a subview of the parent view you want it in or not.

When adding views programmatically through code, they can also be removed through code as well. This can be achieved by calling the removeFromSuperview method on the view. The following line of code shows you how this can be achieved:

[self.subView removeFromSuperview];

See also The Using labels to display text recipe

The Building the user interface for our application recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

The Creating outlets to Interface Builder objects recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

Using labels to display textIn this recipe, we will take a look at how we use labels to display informative text to the user.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

49

Getting readyThe UILabel objects are one of the ways in which we can let users know what is happening. These can be if we are requesting the user to enter his/her username or password, or to inform him/her if something went wrong.

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

3. From Object Library, drag a Label object onto the subview.

4. Resize the Label control so that its contents fi ll the width of the view.

5. Next, create the outlet and properties for this Label control, and name it lblInfo.

6. Our next step is to create the code functionality that will be responsible for setting the label properties with some default values.

7. Open the ViewController.m implementation fi le from the project navigator.

8. Next, create the updateLabel method, as shown in the following code snippet:

-(void)updateLabel{ lblInfo.text = @"Press button to change the background color"; lblInfo.textColor = [UIColor blueColor]; lblInfo.textAlignment = NSTextAlignmentLeft; lblInfo.adjustsFontSizeToFitWidth = TRUE; lblInfo.font = [UIFont fontWithName:@"Arial-Bold" size:17];}

9. Then, add the following code snippet within theviewDidLoad method, as shown next:

- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, // typically from a nib. [self updateLabel];}

10. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

50

How it works…We have successfully added a UILabel object to our view, and added some code to update the contents. We fi rst created the method that will be responsible for customizing the label properties and then we assign some text that needs to be displayed to the Label control's text property.

In our next step, we set the textColor property of the Label control to blue by using the UIColor class values and then we set the textAlignment property so that our label contents will be displayed as left aligned.

Finally, we set the adjustFontSizeToFitWidth property of the label to TRUE to instruct the label to automatically change the font size so that it can fi t inside the width of the label. Next, we add a call to this method into our viewDidLoad method to update the label contents at runtime.

There's more…With labels you can set the font that you want your text to be displayed in; this is achieved by setting the font property using the UIFontfontWithName method. The string parameter represents the name of the font to set and the style, while the size property parameter determines the font size. If you take a look at the following line of code, you can see how to set the font of the label to Arial-Bold and size of 17 points, as follows:

[UIFont fontWithName:@"Arial-Bold" size:17];

If the entered font name is not found, the fontWithName method returns nil and this will cause an exception if the font property of the label is set to nil.

If you would like to fi nd out more information on the UIFont class, you can refer to the Apple Developer documentation located at http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIFont_Class/Reference/Reference.html.

See also The Displaying and editing text recipe

The Obtaining user input through the use of buttons recipe

The Building the user interface for our application recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

The Creating outlets to Interface Builder objects recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

51

Obtaining user input through the use of buttons

In this recipe, we will take a look at how we use buttons to change the contents of a UILabel control that we defi ned in the previous recipe.

Getting readyIn this recipe, we will start by creating a UIButton object that will be used to modify the background color of a label when it is tapped.

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

3. From Object Library, drag a Round Rect Button object onto the subview and place it underneath the label we added previously.

4. From the Attributes Inspector section, modify the Title property to read Tap Here.

5. Next, create the outlet and properties for this Round Rect Button object, and name it btnTapHere.

6. Next, create the action method for the Tap Here button and name it btnTapHere.

7. After adding the button, save the document by selecting File | Save from the menu bar, or alternatively by pressing command + S. The main view should now look like the following screenshot:

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

52

Our next step is to create the code functionality that will be responsible for changing the background color of our label:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Next, create the btnTapHere method, as shown in the following code snippet:

- (IBAction)btnTapHere:(UIButton *)sender {[self.lblInfo setBackgroundColor:[UIColor yellowColor]];}

3. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

How it works…We started by adding a button to our user interface that changed the background contents of a label when the button was pressed. We then call the setBackgroundColor method to apply the background color to our label.

If you would like to fi nd out more information on the UIButton class, you can refer to the Apple Developer documentation located at http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html.

There's more…The functionality provided by the setBackgroundColor method can also be accomplished by setting the Background fi eld in the Attributes Inspector tab within Interface Builder.

See also The Adding and customizing views recipe

The Using labels to display text recipe

The Displaying an image within the view recipe

The Building the user interface for our application recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

The Creating outlets to Interface Builder objects recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

53

Displaying an image within the viewIn this recipe, we will take a look at how we can use the UIImageView class to display images within a view.

Getting readyIn this recipe, we will start by creating a UIImageView object that will be used as a container to display our image. For this example, we will be using an image fi le named Blue-Aqua-Apple.png.

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

3. From Object Library, drag a UIImageView object onto the subview and place it underneath the Round Rect Button object we added previously.

4. Resize the UIImageView control so that it will be big enough to hold the image.

5. Next, create the outlet and property for this UIImageView, and name it imgPicture.

6. Then, select Files | Add Files to "ViewObjectsExample"…, or alternatively press option + command + A.

7. Select the Blue-Aqua-Apple.pngimage fi le to add and then click on the Add button.

Our next step is to create the code functionality that will be responsible for displaying the image within our imageView control:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Next, create the displayImage method, as shown in the following code snippet:

-(void)displayImage{ [self.imgPicture setImage:[UIImage imageNamed:@"Blue-Aqua-Apple.png"]]; [self.imgPicture setContentMode:UIViewContentModeScaleAspectFit];}

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

54

3. Then, add the following line of code within the viewDidLoad method:

[self displayImage];

4. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear, displaying the image that we just added to our project.

How it works…The UIImageView class is basically a view that has been customized for the purpose of displaying images. We then set the contentMode property of the imageView class to UIViewContentModeScaleAspectFit, which scales and fi lls the image to fi t the entire contents of UIImageView.

If you would like to fi nd out more information on the UIImageView class, you can refer to the Apple Developer documentation located at http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIImageView_Class/Reference/Reference.html.

The contentMode property accepts an enumeration type named UIViewContentMode. The following table explains some of these types:

Content mode DescriptionScaleToFill This is the default value. It scales the content to fit the size of the view,

changing the aspect ratio as necessary.

ScaleAspectFit This scales the content to fit the size of the view, while maintaining its aspect ratio. The remaining area of the view becomes transparent.

ScaleAspectFill This scales the content to fill the size of the view, while maintaining its aspect ratio.

There's more…The UIImage class is the object that represents image-related information. The following table displays some of these fi le formats that it currently supports:

File format File extension

Portable Network Graphics .png

Joint Photographic Experts Group .jpg, .jpeg

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

55

File format File extension

Tagged Image File Format .tiff, .tif

Graphics Interchange Format .gif

Windows Bitmap Format .bmp

Windows Icon Format .ico

See also The Adding and customizing views recipe

The Selecting images and video from the camera roll recipe in Chapter 7, Multimedia Resources

The Capturing media with the camera recipe in Chapter 7, Multimedia Resources

Displaying and editing textIn this recipe, we will learn how to use text block methods to determine when editing has begun and ended.

Getting readyIn this recipe, we will discuss the usage of the UITextField object and how we can display editable text within it.

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

3. From Object Library, drag a TextField object onto the subview and place it underneath UIButton we added previously.

4. Resize the TextField control width so that it is big enough to hold enough text.

5. Next, create the outlet and property for this TextField, and name it txtTextInput.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

56

Our next step is to create the code functionality that will be responsible for displaying some text within our TextField control:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Next, create the populateTextBox method, as shown in the following code snippet:

-(void)populateTextBox { self.txtTextInput.text = @"This is some sample text"; self.txtTextInput.returnKeyType = UIReturnKeyDone; self.txtTextInput.delegate = self;}

3. Then, add the following line of code within the viewDidLoad method:

[self populateTextBox];

Our next step is to modify our ViewController.h interface fi le so that we can access the methods for our textbox. This can be achieved by performing the following simple steps:

1. Open the ViewController.h interface fi le from the project navigator.

2. Next, enter the following code snippet:

// ViewController.h// ViewObjectsExample// Created by Steven F Daniel on 15/09/12.// Copyright (c) 2012 GenieSoft Studios. All rights reserved.

#import<UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>{ IBOutlet UITextField *txtTextInput;}@property (weak, nonatomic) IBOutlet UITextField *txtTextInput;

Next, we need to modify our ViewController.m implementation fi le to include the method events for our textbox. This can be achieved by performing the following simple steps:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Next, type in the following code snippet:

-(BOOL)textFieldShouldReturn:(UITextField *)textField { // Dismisses the keyboard when the "Done" button is clicked [textField resignFirstResponder]; return YES;}

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

57

-(void) textFieldDidBeginEditing:(UITextField *)textField{ lblInfo.text = @"TextField contents are being updated"; [self.lblInfo setBackgroundColor:[UIColor redColor]];}

-(void)textFieldDidEndEditing:(UITextField *)textField{ lblInfo.text = @"TextField contents have now been updated."; [self.lblInfo setBackgroundColor:[UIColor greenColor]];}

3. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear and display the textbox with our populated sample text, as shown in the following screenshot:

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

58

How it works…In the following code snippet, we update the text property of the textField control and then set the returnKeyType property to dismiss the keyboard when the Done button is clicked and then set the delegate for the control to be our view controller:

-(void)populateTextBox { self.txtTextInput.text = @"This is some sample text"; self.txtTextInput.returnKeyType = UIReturnKeyDone; self.txtTextInput.delegate = self;}

Next, the UITextField class provides an object that displays editable text. In order for us to respond to the events of our textbox, we need to defi ne a protocol class of UITextBoxDelegate that will act as the textbox's delegate, so that we can determine when text is being modifi ed.

@interface ViewController : UIViewController <UITextFieldDelegate>{ IBOutlet UITextField *txtTextInput;}@property (weak, nonatomic) IBOutlet UITextField *txtTextInput;

In the following code snippet, we declare the textFieldShouldReturn: method of our TextField control. This method handles the dismissing of the keyboard when the Done button is pressed which is achieved by calling the resignFirstReponder method on the TextField control, causing the control to lose focus.

-(BOOL)textFieldShouldReturn:(UITextField *)textField { // Dismisses the keyboard when the "Done" button is clicked [textField resignFirstResponder]; return YES;}

Next, we declare the textFieldDidBeginEditing: and textFieldDidEndEditing: methods of our TextField control. These methods are responsible for determining when text is being updated within the text fi eld and when the editing has been completed, which is achieved when the keyboard is dismissed.

-(void) textFieldDidBeginEditing:(UITextField *)textField{ lblInfo.text = @"TextField contents are being updated"; [self.lblInfo setBackgroundColor:[UIColor redColor]];}

-(void)textFieldDidEndEditing:(UITextField *)textField{

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

59

lblInfo.text = @"TextField contents have now been updated."; [self.lblInfo setBackgroundColor:[UIColor greenColor]];}

There's more…A delegate in Objective-C is a certain type of object that conform to a specifi c protocol. This means that it is an object that wraps one or more methods (and/or other members) that act as event handlers.

See also The Using the iOS device keyboard recipe

Using the iOS device keyboardIn this recipe, we will learn how to set some of the different virtual keyboard styles.

Getting readyIn this recipe, we will discuss the usage of the UITextBox object and how we can display editable text within it.

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Open the ViewController.m implementation fi le from the project navigator.

3. Next, modify the populateTextBox method, as shown in the highlighted lines of the following code snippet:

-(void)populateTextBox { self.txtTextInput.text = @"This is some sample text"; self.txtTextInput.keyboardType = UIKeyboardTypeNumbersAndPunctuation; self.txtTextInput.returnKeyType = UIReturnKeyDone; self.txtTextInput.delegate = self;}

4. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

60

When the compilation completes, the iOS Simulator will appear and display the textbox with our populated sample text. Tap into the TextField control to display our specifi ed keyboard type.

How it works…In the following code snippet, we update the keyboardType property of the TextField control and then specify UIKeyboardTypeNumbersAndPunctuation as the keyboard type to use.

-(void)populateTextBox { self.txtTextInput.text = @"This is some sample text"; self.txtTextInput.keyboardType = UIKeyboardTypeNumbersAndPunctuation; self.txtTextInput.returnKeyType = UIReturnKeyDone; self.txtTextInput.delegate = self;}

The keyboardType property accepts an enumeration type named UIKeyboardType. The following table explains some of these types:

Keyboard type DescriptionUIKeyboardTypeDefault The default keyboard for the current input method

UIKeyboardTypeASCIICapable Displays standard ASCII characters

UIKeyboardTypeNumbersAndPunctuation

Displays numbers and punctuation keyboard

UIKeyboardTypeURL Displays a keyboard optimized for URL entry

UIKeyboardTypeNumberPad Displays a numeric keypad designed for PIN entry

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

61

Keyboard type DescriptionUIKeyboardTypePhonePad Displays a keypad designed for entering telephone

numbers

UIKeyboardTypeNamePhonePad Displays a keypad designed for entering a person's name or phone number

UIKeyboardTypeEmailAddress Displays a keyboard optimized for specifying e-mail addresses

UIKeyboardTypeDecimalPad Displays a keyboard with numbers and a decimal point

UIKeyboardTypeTwitter Displays a keyboard optimized for twitter text entry, with easy access to the @ and # characters

UIKeyboardTypeAlphabet This has been depreciated, but uses the keyboard that displays standard ASCII characters

If you would like to fi nd out more information on the UIKeyboardType class, you can refer to the Apple Developer documentation, located at http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITextInputTraits_Protocol/Reference/UITextInputTraits.html.

See also The Adding and customizing views recipe

The Obtaining user input through the use of buttons recipe

The Displaying and editing text recipe

Displaying the progress to the userIn this recipe, we will learn how we can display the progress of any given length.

Getting readyIn this recipe, we will discuss the usage of the UIProgressBar object and how we can use the associated properties to display an animated progress bar.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

62

How to do it...In order to see how this can be achieved, we need to modify the ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

3. From Object Library, drag a ProgressView object onto the subview and place it underneath the UIImageView we added previously.

4. Resize the ProgressViewcontrol so that its width is as wide as the view.

5. Next, create the outlet and property for this ProgressView, and name it pgbProgress.

Our next step is to create the code functionality that will be responsible for displaying the progress and animating the bar:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Type in the variable declaration highlighted in the following code snippet:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize subView;@synthesize lblInfo;@synthesize pgbProgress;@synthesize imgPicture;@synthesize txtTextInput;

float incrementBy = 0.0;

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

63

3. Next, modify the btnPressMe method, as shown in the highlighted line of the following code snippet:

- (IBAction)btnTapHere:(UIButton *)sender {

[self fillProgressBar]; [self.lblInfo setBackgroundColor:[UIColor yellowColor]];}

4. Next, type in the following code snippet:

- (void)fillProgressBar { [self.pgbProgress setProgress:(incrementBy = 0.0f)]; [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(incrementBar:) userInfo:nil repeats:YES];}

-(void)incrementBar:(NSTimer *)timer{ incrementBy += 10.0f; [pgbProgress setProgress:(incrementBy / 100)]; if (incrementBy > 100.0) { self.lblInfo.text = @"Processing has been Completed"; [timer invalidate]; } else { self.lblInfo.text = [NSString stringWithFormat:@"Processing data records: %3.2f", (pgbProgress.progress * 100)]; }}

5. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

64

When the compilation completes, the iOS Simulator will appear. Click on the Tap Here button to see the progress bar fi ll gradually, as shown in the following code snippet:

How it works…In the following line of code, we declare a float variable incrementBy. This variable will be used by our method to gradually increment and fi ll the progress bar.

float incrementBy = 0.0;

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

65

Next, we modify our btnTapHere: method to include a call to our method, fillProgressBarmethod that will be responsible for handling the processing, as well as calling other methods to gradually fi ll the bar.

- (IBAction)btnTapHere:(UIButton *)sender {

[self fillProgressBar]; [self.lblInfo setBackgroundColor:[UIColor yellowColor]];}

In our next code snippet, the fillProgressBar method initializes the incrementBy variable to 0 to make sure that the bar is not fi lled at all. We then use the scheduledTimerWithTimeInterval method, which is one of the class methods of the NSTimer class, which is used to create timers.

NSTimer is an object that is scheduled to run within the run loop, so that it can check time passed periodically. When enough time has passed, it fi res. If the timer has been set up to be non repeating, it then unschedules itself, otherwise it clears its elapsed time and waits to fi re again. Next, we specify the duration in seconds when to call the incrementBar: method, as specifi ed by the selector property and keep calling this method until the timer is invalidated.

- (void)fillProgressBar { [self.pgbProgress setProgress:(incrementBy = 0.0f)]; [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(incrementBar:) userInfo:nil repeats:YES];}

In our fi nal code snippet, we start by setting our incrementBar variable to the number of incremental steps this should take to fi ll our progress bar value, and then update the progress property of our ProgressView. Next, we check to see if we have reached our bar threshold and then update the label accordingly, before fi nally invalidating our timer object to prevent the method from being called.

Alternatively, if we have not yet reached our threshold, we update the Label object to show the progress bar's current progress.

-(void)incrementBar:(NSTimer *)timer{ incrementBy += 10.0f; [pgbProgress setProgress:(incrementBy / 100)]; if (incrementBy > 100.0) { self.lblInfo.text = @"Processing has been Completed"; [timer invalidate]; } else { self.lblInfo.text = [NSString

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

66

stringWithFormat:@"Processing data records: %3.2f", (pgbProgress.progress * 100)]; }}

If you would like to fi nd out more information on the NSTimer class, you can refer to the Apple Developer documentation, located at https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html.

There's more…The UIProgressView class supports one more style. This can be specifi ed by setting the progressViewStyle property to UIProgressViewStyleBar. With that change, the bar will look like the one, as can be seen when using Apple's Mail application.

See also The Adding and customizing views recipe

The Using labels to display text recipe

The Obtaining user input through the use of buttons recipe

Adding a toolbar to a viewIn this recipe, we will learn how to add and use toolbars within our application.

Getting readyIn this recipe, we will discuss the usage of the Toolbar object and how we can use the associated properties to display an animated progress bar.

How to do it...In order to see how this can be achieved, we need to modify our ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.xib fi le from the project navigator window.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

67

3. From Object Library, drag a Toolbar object into the main view controller, and place it at the top of the main view.

4. Next, select the button it contains by default and set its Title property to Fade In.

5. Next, add a Flexible Space Bar Button Item object to the toolbar to the right of the Fade In button.

6. Then, from Object Library, drag a UIBarButtonItem object to the toolbar and place this after the Flexible Space Bar Button Item object.

7. Next, select the button and set its Title property to Fade Out.

8. Next, create the outlets and properties for the Fade In and Fade Out buttons, and name them btnFadeIn and btnFadeOut.

9. Next, create the action methods for the Fade In and Fade Out buttons, and name them viewFadeIn and viewFadeOut.

10. After creating the button outlets and properties, save the document by selecting File | Save from the menu bar, or alternatively by pressing command + S. The layout should look like the following screenshot:

Our next step is to create the code functionality that will be responsible for updating the label to display what button was pressed within the toolbar:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Modify the viewFadeIn and viewFadeOut methods, as shown in the following code snippet:

- (IBAction)viewFadeIn:(UIBarButtonItem *)sender {lblInfo.text = @"Fade In button clicked.";}

- (IBAction)viewFadeOut:(UIBarButtonItem *)sender {lblInfo.text = @"Fade Out button clicked.";}

3. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear. Tap on both of the toolbar buttons to see the label update based on which button has been clicked.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

68

How it works…The UIToolbar object is used to hold items relating to the UIBarButtonItem object type. These types of objects are special kinds of buttons and spacers. A UIBarButtonItem object can be system defi ned or custom type, and can use any of the predefi ned types as listed in the Identifi er attribute within Interface Builder and provides a specifi c icon to the button.

The UIBarButtonItem objects can also be customized to contain an image to make your application more professional and visually intuitive. This can be achieved by using the Image attribute within Interface Builder.

There's more…The UIBarButtonItem class has a style property that determines the button's style. It can be used only when the button item's identifi er is set to Custom. You can set the button's style property to any of the UIBarButtonItemStyle types.

See also The Adding and customizing views recipe

The Using labels to display text recipe

Fading a view in and outIn this recipe, we will take a look at how we can perform some fancy animations to views. These can be perfect for building and enhancing the user experience to produce smooth, animated animations for your applications.

Getting readyThe UIView animations are the perfect building blocks for building the visual bridge between a view's current and changed state. With views, you can visually change and create animations that link these together. Some examples include the following:

Moving a view around the screen

Updating the view's frame and bounds coordinates

Stretching the view's content to fi ll the screen regions

Altering the view's alpha value to support transparency

Hiding or showing a view

Altering the view's ordering to show which view is in front

Performing transformations and rotations to views

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

69

How to do it...In order to see our view fade in and out, we need to modify our ViewObjectsExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the ViewObjectsExample.xcodeproj project fi le.

2. Select the ViewController.m implementation fi le from the project navigator.

3. Next, modify the viewFadeIn method, as shown in the following code snippet:

- (IBAction)viewFadeIn:(UIBarButtonItem *)sender {

[UIView beginAnimations: @"Fade In" context:nil]; [UIView setAnimationDuration:2.0]; [self.subView setAlpha:1.0f]; [UIView commitAnimations];

// Disable our FadeIn Button since we are processing [self.btnFadeOut setEnabled:YES]; [self.btnFadeIn setEnabled:NO];}

4. Next, modify the viewFadeOut method, as shown in the following code snippet:

- (IBAction)viewFadeOut:(UIBarButtonItem *)sender {

[UIView beginAnimations: @"Fade Out" context:nil]; [UIView setAnimationDuration:2.0]; [self.subView setAlpha:0.0f]; [UIView commitAnimations];

[self.btnFadeOut setEnabled:NO]; [self.btnFadeIn setEnabled:YES];}

5. Then, add the highlighted code lines of the following code snippet to the viewDidLoad method:

- (void)viewDidLoad{ [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib. [self updateLabel]; [self displayImage]; [self populateTextBox];

[self.pgbProgress setProgress:0.0 animated:YES]; [self.btnFadeOut setEnabled:YES]; [self.btnFadeIn setEnabled:NO];}

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

70

6. Then, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear. Tap on both of the toolbar buttons to see the subview's start to fade either in our out.

How it works…In the following code snippet, we mark the start of our animation block using the beginAnimations method and specify the Fade In animation type, before setting the graphics context to nil. Next, we specify the length of the animation in seconds using setAnimationDuration, and then set the alpha transparency layer by setting setAlpha to 1.0, which makes it become visible.

Finally, we use the commitAnimations method to indicate that all of our properties to animate have been set, and animations should begin and then enable/disable our toolbar buttons accordingly.

- (IBAction)viewFadeIn:(UIBarButtonItem *)sender {

[UIView beginAnimations: @"Fade In" context:nil]; [UIView setAnimationDuration:2.0]; [self.subView setAlpha:1.0f]; [UIView commitAnimations];

// Disable our FadeIn Button since we are processing [self.btnFadeOut setEnabled:YES]; [self.btnFadeIn setEnabled:NO];}

Next, we mark the start of our animation block using the beginAnimations method and specify the Fade Out animation type, before setting the graphics context to nil. We then specify the length of the animation in seconds using setAnimationDuration, and then set the alpha transparency layer by setting setAlpha of our subview to invisible so that it gradually fades.

Finally, we use the commitAnimations method to indicate that all of our properties to animate have been set, and animations should begin and enable our Fade In button within our toolbar.

- (IBAction)viewFadeOut:(UIBarButtonItem *)sender {

[UIView beginAnimations: @"Fade Out" context:nil]; [UIView setAnimationDuration:2.0]; [self.subView setAlpha:0.0f]; [UIView commitAnimations];

[self.btnFadeOut setEnabled:NO]; [self.btnFadeIn setEnabled:YES];}

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

71

If you would like to fi nd out more information on UIView animations, you can refer to the Apple Developer documentation, located at http://developer.apple.com/library/ios/#documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW131.

See also The Adding and customizing views recipe

The Adding a toolbar to a view recipe

Creating a custom table view controllerIn this recipe we will learn how to create a subclass of the UITableViewController class, and use it to populate a UITableView controller.

Getting readyThe UITableViewController classes are a perfect way of providing you with the fl exibility to manage a table view, and providing the functionality of adding to our base controller the ability of sharing its inheritor classes. For this to happen, we will need to incorporate the methods for a UITableView class.

How to do it...To begin, we will need to create a new Xcode project. This can be achieved by performing the following simple steps:

1. Create a new Single View Application project and name it TableViewExample.

2. Next, select the TableViewExample folder, select File | New | New File… or press command + N.

3. Select the Objective-C class template from the list of templates.

4. Click on the Next button to proceed to the next step in the wizard.

5. Enter TableViewController as the name of the fi le to create.

6. Ensure that you have selected UITableViewController as the type of subclass to create from the Subclass drop-down menu.

7. Ensure that the Targeted for iPad checkbox is not checked.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

72

8. Ensure that the With XIB for User Interface checkbox is not checked.

9. Click on the Next button to proceed to the next step of the wizard.

10. Click on the Create button to save the fi le to the specifi ed folder location.

How it works…What we have done here is add a new TableViewController class to our TableViewExample application that provides us with the necessary table view methods we can use to interact with the TableView control.

See also The Adding a table view to a view controller recipe

The Using Xcode to create an iOS project recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

Adding a table view to a view controllerIn this recipe we will learn how to add a UITableView object to an existing view controller.

Getting readyThe UITableView object provides you with an interface for displaying data in list form.

How to do it...In order to add a table view to our view controller, we need to modify our TableViewExample application that we created in the previous recipe. Perform the following steps to do so:

1. Open the TableViewExample.xcodeproj project fi le.

2. Next, change the inheritance of the ViewController class, as shown in the following highlighted line of code:

@interface ViewController : UITableViewController

3. Next, select the ViewController.xib file from the project navigator window.

4. Then, delete the current view within the view controller, by selecting it and then pressing the Delete key.

5. Next, from Object Library, drag a TableView object onto the drawing area.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

73

6. Hold down the control key and drag from the File's Owner object to the UITableView, as shown in the following screenshot:

7. Select view from the pop-up panel and release the button. This connects the TableView we have just added to the view outlet of the File's Owner object.

Our next step is to modify the ViewController class to use the custom table view controller that we created in the previous recipe. This can be achieved by performing the following simple steps:

1. Click and select the File's Owner controller object within the view.

2. Then, select the Identity Inspector section and change the value of the Custom Class property to read CustomTableView, as shown in the following screenshot:

3. Save the document by selecting File | Save from the menu bar, or alternatively by pressing command + S.

4. Next, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

74

How it works…When we add a UITableView object to an existing view using Interface Builder, its view is displayed with some predefi ned data, which is only visible during design time and not at runtime.

We then hooked up the view of our TableView object to our File's Owner object, and fi nally we modifi ed the view controller's class to use our own CustomTableView class that we created. The discussion on how to go about populating data in UITableView will be covered in an upcoming chapter.

See also The Creating a custom table view controller recipe

The Creating an iOS Project with Xcode recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

The Displaying data within the table view recipe in Chapter 8, Data Management

Handling different iOS devicesIn this recipe, we will learn how to detect whether we are running the application on an iPhone or iPad device.

Getting readyThe UIDevice object provides you with various methods that allow you to gain access to certain information relating to a specifi c device; it can help you work out how much battery is remaining on the device, as well as determine what type of device it is and its orientation aspects.

How to do it...To begin, we will need to create a new Xcode project. This can be achieved by performing the following simple steps:

1. Create a new Single View Application project and name it UniversalApp.

2. Next, select the ViewController.xib fi le from the project navigator window.

3. Next, from Object Library, drag a Label object onto the main view.

4. Resize the Label control so that its contents fi ll the width of the view.

5. Next, create the outlet and property for this Label control, and name it lblMessage.

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

75

Our next step is to create the code functionality that will be responsible for determining what type of iOS device we are using, as well as updating the label properties. This can be achieved by performing the following simple steps:

1. Open the ViewController.m implementation fi le from the project navigator.

2. Next, modify the viewDidLoad method, as shown in the following code snippet:

- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { self.view.frame = CGRectMake(0, 0, 768, 1024); self.lblMessage.text = @"I'm running on the iPad"; self.view.backgroundColor = [UIColor yellowColor]; self.lblMessage.font = [UIFont systemFontOfSize:18.5f]; self.lblMessage.adjustsFontSizeToFitWidth = TRUE; } else { self.lblMessage.text = @"I'm running on an iPhone"; self.view.backgroundColor = [UIColor blueColor]; self.lblMessage.font = [UIFont systemFontOfSize:18.5f]; self.lblMessage.adjustsFontSizeToFitWidth = TRUE; }}

3. Save the document by selecting File | Save from the menu bar.

4. Next, select UniversalApp from the project navigator.

5. In the Summary tab, select Universal from under the Devices drop-down menu, as shown in the following screenshot:

For More Information: www.packtpub.com/xcode-4-cookbook/book

User Interfaces – Creating the UI

76

6. Next, switch between the different devices by clicking inside the highlighted section, as shown in the following screenshot:

7. Build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

How it works…In the following code snippet, we check to see which device the application is running on, by checking the userInterfaceIdiom property of the UIDevicecurrentDevice property:

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

If an iPad has been determined, we resize the view using the frame property to size it to the iPad screen's dimensions and then update our label properties and then set the background of our view, as shown in the following code snippet:

self.view.frame = CGRectMake(0, 0, 768, 1024);self.lblMessage.text = @"I'm running on the iPad";self.view.backgroundColor = [UIColor yellowColor];self.lblMessage.font = [UIFont systemFontOfSize:18.5f];self.lblMessage.adjustsFontSizeToFitWidth = TRUE;

Alternatively, if it has been determined that we are running the application on an iPhone, we update our label properties and then set the background of our view, as shown in the following code snippet:

else { self.lblMessage.text = @"I'm running on an iPhone"; self.view.backgroundColor = [UIColor blueColor]; self.lblMessage.font = [UIFont systemFontOfSize:18.5f]; self.lblMessage.adjustsFontSizeToFitWidth = TRUE; }

For More Information: www.packtpub.com/xcode-4-cookbook/book

Chapter 2

77

If you would like to fi nd out more information on the UIDevice class, you can refer to the Apple Developer documentation, located at http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html.

See also The Adding and customizing views recipe

The Using labels to display text recipe

The Creating outlets to Interface Builder objects recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

The Using Xcode to create an iOS project recipe in Chapter 1, Getting and Installing the iOS SDK Development Tools

For More Information: www.packtpub.com/xcode-4-cookbook/book

Where to buy this book You can buy Xcode 4 Cookbook from the Packt Publishing website: http://www.packtpub.com/xcode-4-cookbook/book. Free shipping to the US, UK, Europe and selected Asian countries. For more information, please read our shipping policy.

Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet book retailers.

www.PacktPub.com

For More Information: www.packtpub.com/xcode-4-cookbook/book