Showing posts with label IPhone - development - UI. Show all posts
Showing posts with label IPhone - development - UI. Show all posts

Tuesday, April 26, 2011

Ways to add new view to current view

There are at least 3 ways to add a new view to the current view:
  1. addSubView
  2. pushViewController
  3. presentModalViewController
Below are some comparisons between the above methods:


Feature

addSubView  /
insertSubView

pushViewController

presentModalViewController
Usage
It is typically use to create view heirarchy
programmatically. A view heirarchy will consist of multiple subviews that make up different components in the view.

Each sub view will has its own draw and animation handling.
Each sub view also has its own event handling. Alternatively, view heirarchy can
be created using Interface Builder.
In many IPhone application, the user will need to go through different pages of form / view to complete a specific workflow for a task. Typically, pushViewController is used to step the user through the different pages to complete the task. It is usually work with navigation controller. Push view controller will create the visual effect of push page left to right.In some IPhone application, while performing a task, the user will need to complete a self-contained subtask before he can continue the task. Modal view mechanism can be used to accomplish the subtask function. By default, the present modal viewController will slide a set of controls from bottom to top to the current view. The modal view need to be dismissed before the user can continue with the current view.
Compatibility with navigationController tabBarControllerUsually the subview will be added to the top of the current view, hence cover the navigation bar. The toolbar may also be covered depending on  the size of the subview. The subview can use setFrame to position it below the navigation controller.
Eg:
[self.view setFrame:CGRectMake(0,60,320,400)];
Work well with tabBarController, navigationControllerBoth controllers will be hidden from the modal view. Except for partialCurl transitionStyle. which the NavigationBar will
still be visible.
Return back from the added viewHas to implement return mechanism.Can have automatic back button created
if
the root Controller is navigation controller and the back barButtonItem is created in the root navigation
controller. ** For default back button to work, each
view must has title setted.
Has to implement return mechanism.
Sample code:
Add newViewController
[self.viewController.view
addSubView: newViewController.view];
[self.viewController
pushViewController: newViewController];
[self.viewController
presentModalViewController: newViewController];
Sample code:
Remove
newViewController
[self.view removeFromSuperView];[self.viewController popViewController
Animated: YES];
[self dismissModalViewController
Animated: YES];

Tuesday, April 19, 2011

Creating Modal View

In a typical Windows environment, modal window is a child or popup window where user can not press on any control on the parent window before complete and close the child or popup modal window.

For IPhone or IPad application, modal view behave the same. Sometime it is neccessary to popup a modal view to the user for data entry or other action view which the user has to complete the data entry view before the user can proceed to other part of the application.

The following steps outline how such modal view can be acheived:

1. Create a UIViewController subclass, by New File -> Cocoa   touch -> UIViewController subclass.
    Ensure that the "With XIB for user interface" option is selected.
    eg.  create a UIViewController subclass -> ModalController

2. Use interface builder to create the needed UI in the created ModalController.

3. Add the following modal view invocation code in the appropiate section:

ModalController* modal = [[ModalController alloc] initWithNibName:Nil bundle:Nil];
[modal setModalTransitionStyle:UIModalTransitionStylePartialCurl];  // this will determine how the modal transition in
[modal setModalPresentationStyle:UIModalPresentationFullScreen];  // this will how the modal will be presented
[self.navigationController presentModalViewController:modal animated:YES];

4. Add the following modal view removal code in the appropiate section, eg. link to the exit button of the ModalController:

- (IBAction) backToMain: (id) sender {
    [self dismissModalViewControllerAnimated:YES];
}

Monday, April 18, 2011

Creating application without status bar

The status bar in an iphone application shows the network connections (Telco, WIFI, bluetooth.. etc), date, battery usage, location icon... etc.
For some application, it may be usefull to hide the status bar so that the application has maximum screen area.

To hide the status bar, send the setStatusBarHidden message to the UIApplication object. It should be send in the UIApplication's didFinishLaunchingWithOptions method. This method will be invoked when the application finish launching.

eg.

   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)
      launchOptions  {
            ..... 
            [[UIApplication sharedApplication]setStatusBarHidden:YES];
            .......
   }

Sunday, April 10, 2011

Creating UITableView

The following steps show how to create UITableView in a iPhone application, it is very similar to the UIPickerView implementation:
1. Create the UITableView in interface builder.
2. Add the IBOutlet for UITableView in the interface (.h) file. (optional, if the UITableView is needed to reference in the code)
3. Link the IBOutlet for UITableView to the UITableView in interface builder. (optional, only if the IBOutlet is created in step2)
4. Implement the following datasource and delegate methods for basic browsing function:
    a.  numberOfRowsInSection datasource method should return the number of row in the table.
        eg.
    - (NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection: (NSInteger)section {
          return [array count];
    }
    b.  cellForRowAtIndexPath datasource method should return a table cell for the row at the indexPath for the table.
        eg.
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
          (NSIndexPath *)indexPath {
               UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];    }
               if (cell==NULL) {
                  cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"]
                            autorelease];
              }
             cell.text= [array objectAtIndex:indexPath.row];          // cell.text is deprecated
            return cell;
    }
    c. numberOfSectionsInTableView datasource method should return the number of sections in the UItableView.   
      (Optional, only for multiple section UITableView)
       eg.
          - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
             return numberOfSections;
         }
    d. titleForHeaderInSection datasource method should return the header of the section.
       (Optional, only needed for multiple sections UITableView)
       eg.
       - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
           if (section == 0)   return @"section 1";
           else if (section ==1)   return @"section 2";
           // more code to return header ......
       }
     e. didSelectRowAtIndexPath delegate method would be called if the user selected a row in the UITableView.
        (Optional, only needed if there are actions to be performed when user selected a row)
        eg.
       - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
           // actions to be performed...
           // indexPath.section will give the selected section
           // indexPath.row will give the selected row
           // can implement show detail view....
       }
       f. accessoryTypeForRow delegate method should return the type of accessory (like button, arrow...).
       (Optional, only needed if button or arrow accessory is needed to display at the side)
       eg.
       - (UITableViewCellAccessoryType)tableView:(UITableView *)tableView
          accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
                //return UITableViewCellAccessoryDetailDisclosureButton;  
               //return UITableViewCellAccessoryDisclosureIndicator;
               
               //return UITableViewCellAccessoryNone;
                //return UITableViewCellAccessoryCheckmark;  
       }
       g. accessoryButtonTappedForRowWithIndexPath delegate method would be invoked when the user clicked on the accessoryButton.
      (Optional, only needed if button in step f is setted)
        eg.
          - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:
            (NSIndexPath *)indexPath {
                 // invoke a method here
                 // eg. [self tableView:tableView didSelectRowAtIndexPath:indexPath];
          }
5. The following steps describe how to implement delete function for UITableView:
    a. Set the tableView into editing mode. There are two ways to set a tableView into editing mode:
        i. tableView.editing property set to YES
        eg.
            tableView.editing = YES;
            // or [tableView setEditing:YES animated:YES]
        ii. If the tableView has implmented with UINavigationController, set the navigationBarButton (left or right) to editButtonItem. This will allow toggle the tableView into editing mode.
        eg.
           self.navigationItem.rightBarButtonItem = self.editButtonItem;
     b. Implement the commitEditingStyle datasource method. This method will be invoked, when a tableView item is deleted.
       eg.
           - (void)tableView:(UITableView *)tableView commitEditingStyle:
             (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
               
if (editingStyle == UITableViewCellEditingStyleDelete) { 

                        // ... delete code here ....               
                }
           }
6. Link the UITableView's datasource and delegate to the code that implement the above datasource and   
    delegate methods.

7. The tableView can be set with different background color using the setBackgroundColor method.
     Eg.
[self.tableView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];

Sunday, March 20, 2011

Creating UIPickerView

The following steps outline how to create a UIPickerView in an iPhone application.
1. Create the UIPickerView in Interface Builder.
2. Add the IBOutlet for the UIPickerView in the interface file (.h) for the view. Add the @synthesis for the IBOutlet in the objective c code (.m) for the view. (Optional, if the UIPickerView is needed to reference in the code)
eg. in the interface (.h) file
@interface controller : UIViewController {
       IBOutlet UIPickerView *picker;
}
@property (nonatomic, retain) IBOutlet UIPickerView *picker;

eg. in the implementation code (.m) file
@synthesize picker;
3. Link the picker IBOutlet to the UIPickerView in Interface Builder. (optional only if step 2 is followed)
4. The following 1 delegate and 3 datasource methods need to be implemented:
a. numberOfComponentsInPickerView, this datasource method should return the number of components in the UIPickerView. (Optional, only needed for multiple components UIPickerView)
   eg:
   - (NSInteger) numberOfComponentsInPickerView: (UIPickerView *)thePickerView {
         return numberOfComponentsInPickerView;  // this should return the number of components in the UIPickerView
   }
b. numberOfRowsInComponent, this datasource method should return the number of rows in the component.
    eg:
    -(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent: (NSInteger) component {
          return [componentArray count];
    }
c. titleForRow, this datasource method should return the title of the row in the picker view
    eg:
    -(NString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent: (NSInteger) component {
          return [componentArray objectAtIndex:row];
    }

d. didSelectRow, this delegated method will be invoked when user select the item in the picker view.
    (Optional, only needed if some action is needed to perform when user select the item on the UIPickerView)
* When there are multiple components in the picker, this method is only called once, when two components are turned together.
    eg:
    -(void)pickerView:(UIPickerView *)thePickerView didSelectRow: (NSInteger)row inComponent: (NSInteger) component  {
          selectedIndex = row;
     }

5. Link the datasource and delegate for the UIPickerView to the delegate implementation in the Interface Builder.

Friday, August 06, 2010

Auto show keyboard

To automatically show the keyboard in any view for a specific UITextField, just set the UITextField as the first responder in the viewDidLoad method.

Eg:
     - (void)viewDidLoad {

               [super viewDidLoad];
              [commentTxt becomeFirstResponder];


    }

Thursday, August 05, 2010

Programming IPhone to support rotation auto orientation change

Everytime when IPhone is rotated the shouldAutorotateToInterfaceOrientation method is called.
To support this, just return YES.

Eg:
       - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

                  // Return YES for supported orientations
                 return YES;
      }

Wednesday, May 26, 2010

Creating scrollable view

These are the steps for creating an application with scrollable view:
1. Create a scrollable view in the application
  • use either interface builder or code to add a UIScrollView to the current window
  • Sample code to add a scroll view:
            CGRect frame = [CGRectMake(0,0,200,200)];
            UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:frame];


2. Add subviews (frames may extend beyond the above scroll view bounds)
  • Sample code to add subview:


        UIImage* image = [UIImage withName: @"image.jpg"];  /// image.jpg need to be added to resource
             UIImageView imageView = [[UIImageView alloc] initWithImage:image];
             [scrollView addSubview: imageView];


3. Set the content size
  • sample code to set content size:
             [scrollView setContentSize: [image size]];

4. Set the max zoom and min zoom, if zoom is needed
  • sample code to set min and max zoom:
             [scrollView setMaximumZoomScale: 4.0];
             [scrollView setMinimumZoomScale: 0.1];


5. If zoom is needed, implement the ScrollView's viewForZoomingInScrollView delegate
  • sample code for viewForZoomingInScrollView delegate:
             - (UIView *) viewForZoomingInScrollView: (UIScrollView *) scrollView  {
                       return imageView;
             }
6. Implement all the needed and optional delegate if neccessary.
  • Implement scrollViewDidScroll delegate if need to respond to scroll event
    • sample code:
                          - (void) scrollViewDidScroll: (UIScrollView *)scrollView  {
                              if (scrollView.contentOffset ...) {
                                      // do something here
                                }
                          }
  • Set the scrollViewShouldScrollToTop delegate to change the behaviour
    • sample code:
               - (BOOL) scrollViewShouldScrollToTop: (UIScrollView *) scrollView {
                         // return TRUE or FALSE, depending on view should scroll to top
               }

7. When the view is no more needed, to allow user to return to previous view, send the removeFromSuperview message to the viewController.
    • sample code:
      [self.view removeFromSuperview];

Saturday, May 22, 2010

Creating application with UITabBarController

The diagram shows the layout of a typical IPhone application. Each UI component name is also stated in the diagram. Usually an IPhone application has one UITabBarController. When the tab bar is selected, a specific NavigationController is activated. Each Navigation Controller can be pushed with one or more View Controller. Typically other View Controller can be invoked by linking a button to the method that pop the view controller.

  

The hierarchy of the UI component is shown in the diagram below:
Nesting Navigation Controllers in UITabBarController
  • Create UITabBarController
                tabBarController =  [[UITabBarController alloc] init];     
               
  • Create each UINavigationController
               UINavigationController *navController1 = [[UINavigationController alloc] init];
               [navController pushViewController: firstViewController animated: NO];
               // .....  create other UINavigationController
  • Add all the UINavigationController / UIViewController to UITabBarController
              tabBarController.viewControllers = [NSArray arrayWithObjects:
                                                                      navController1,
                                                                      navController2,
                                                                      otherViewController,
                                                                      nil ];
             [window addSubView:tabBarController.view];
The above code is typically add to applicationDelegate viewDidFinishLaunchingWithOptions method.

Customizing the UI controller

The Title on the UINavigationController can be customized by changing the viewController.title field in the viewDidLoad method in the view class. Eg:

                      firstView.title = @"First View";  
  • The TabBarItem image and title can be customized by changing the tabBarItem field in navigationController or viewController. Eg: The customization code can be added to the viewDidLoad method of the viewController.
                        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Playlists"                                                            image: [UIImage imageNamed:@"music.png"]
                                                               tag: 0];
                        self.tabBarItem = item;
                        [item release];
               
  • System item can also be added to the tab bar, Eg:
                  UITabBarItem *item = [[UITabBarItem alloc] initWithTabBarSystemItemItem:    
                                                        UITabBarSystemItemContacts tag:0];                 
                  navigationController.tabBarItem = item;
                  [item release];

    

Friday, May 21, 2010

Customizing UIBarButtonItem and UIToolbarItem on UINavigationController

There are a bar on the top of the application that has UINavigationController. This top bar is typically known as the navigation bar, it can be customized with rightButtonItem, leftButtonItem and the title.

The bottom bar in the UINavigationController is typically known as tool bar. It can be customized with setToolbarItems using an array of UIBarButtonItem.
 
The following outline the step to customize the navigation bar and tool bar buttons:

1. Usually the best place to add the customization code for adding the UINavigationBarItem and UIToolBarItems is in the viewDidLoad method of the UIViewController.

2. To add the UINavigationBarItem,
    a) First create an UIBarButtonItem
    Eg: the below code implement system button
            UIBarButtonItem *butt = [[UIBarButtonItem alloc]
                                                      initWithBarButtonSystemItem: UIBarButtonSystemItemCarmera  
                                                      target:self action:@selector(action)];
   b) Add the newly created custom button to the navigation bar:
   Eg:
            self.navigationItem.rightBarButtonItem = butt;
             // or [self.navigationItem setRightBarButtonItem:butt animated:YES];

3. If back button is needed in all subsequence pushed viewController (to return to parent view),
    the backBarButtonItem is needed to add to the root navigationController. If the title of the
    backBarButtonItem is not set, the default behaviour is that the back button will be created with
    the title of the parent view.
    **Note: For default behaviour to work, all the viewController must be set with a title.
    Eg:
                UIBarButtonItem *backButt = [[UIBarButtonItem alloc]init];
                 [backButt setTitle:@"Back"];
                 [self.navigationItem setBackBarButtonItem:backButt];

4. To add the UIToolbarItems,
    a) First create all the individual needed UIBarButtonItem
     Eg: Below code create the system's action and compose button, and  a custom information button
           Note: the custom information button does not work in the navigation bar
             UIBarButtonItem *butt1 = [[UIBarButtonItem alloc]
                                                      initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                                      target:self action:@selector(getInfo:)];

             UIBarButtonItem *butt2 = [[UIBarButtonItem alloc]      
                                                      initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
                                                      target:self action:@selector(getInfo:)];

             /* Below code create other system button, such as Info Button */
             UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
             [infoButton addTarget:self action:@selector(action)
                               forControlEvents:UIControlEventTouchUpInside];
             UIBarButtonItem *butt3 = [[UIBarButtonItem alloc] initWithCustomView: infoButton];
           
             /***  Below code add a button with image **/
            UIButton* starButt =[UIButton buttonWithType:UIButtonTypeCustom];
           UIImage* buttonImage = [UIImage imageNamed:@"star.png"];
           [starButt addTarget:self action:@selector(getInfo:)        
                           forControlEvents:UIControlEventTouchUpInside];
           [starButt setImage:buttonImage forState:UIControlStateNormal];
           starButt.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
           UIBarButtonItem *butt4 = [[UIBarButtonItem alloc]initWithCustomView:starButt];
      b) Create an array for all the above created UIBarButtonItems.
        eg.
              NSArray* toolBarItems = [NSArray arrayWithObjects:butt1,butt2,butt3,butt4,nil];
     c)  Release all the create UIBarButtonItems
          eg.
              [toolBarItems makeObjectsPerformSelector:@selector(release)];
      d)  Assign the newly created UIBarButtonItem array to the toolBarItems and set it to not hidden (by
           default it is hidden) :
           eg.
                [self setToolbarItems:toolBarItems animated:YES]; // or self.toolbarItems = toolBarItems;
                [self.navigationController setToolbarHidden:NO]; //or self.navigationController.toolbarHidden= NO;

5. Implement the method to handle when the button is clicked.
    eg.
          - (void)action {
               // ... actual code to implement the action
               // ... when the button is clicked
          }

Wednesday, May 19, 2010

Data flow communication between UIViews

There are many ways for two UIViews to exchange data between them. Below list a few of them:

1. Global variable
    This is the least desire way, though it is probably the easiest way. However, this way is most difficult to
    maintain. With this, it is almost impossible to know which UIViews are related. When changes make to
    one, it is also very difficult to assess which other will be impacted.

2. Message passing
    Public variable can be setup in the UIViews. Setter method can be automatically generated by using the
    @synchronize keyword. The setter method can be invoke to pass the message.
    Eg.
                  UIView.title=@"Testing";

3. Delegate
    Setup delegate interface in the UIView that will be call when there are event changes in the calling 
    UIView.

Saturday, May 15, 2010

Creating an UINavigationController application

A UINavigationController can be added to simple IPhone window application, to create a navigation bar on top of the view as shown in the diagram in the right. The following steps show how UINavigationController can be added to a simple IPhone window application:

1.  Add the UINavigationController object in the header file for the
     applicationDelegate.
     Eg. in ApplicationDelegate.h @interface section:
    UINavigationControoller *uiNavCtrl;

2. Add the following codes to the applicationDelegate.m main class in
    the didFinishedLaunchingWithOptions method.
    Eg.
         uiNavCtrl=[[UINavigationController alloc] init]; 
         [window addSubView: uiNavCtrl.view];   

3. After adding the above codes, UINavigationController has to be release in the dealloc method in the
    applicationDelegate.m main class.
     [uiNavCtrl    release];
    An UINavigationController can have multiple UIViewControllers class pushed into it. If more than one
   UIViewController are pushed into the UINavigationController, the last one that is pushed will be
   displayed, when the application is first launched. A Back button will be automatically created if there are
   more than one UIViewController class are pushed. Steps below outline how to add new
   UIViewController to UINavigationController:

4. If back button is needed in all subsequence pushed viewController (to return to parent view),
    the backBarButtonItem is needed to add to the root navigationController. If the title of the
    backBarButtonItem is not set, the default behaviour is that the back button will be created with
    the title of the parent view.
    **Note: For default behaviour to work, all the viewController must be set with a title.
    Eg:
              UIBarButtonItem *backButt = [[UIBarButtonItem alloc]init];
              [backButt setTitle:@"Back"];
              [self.navigationItem setBackBarButtonItem:backButt];

5. Create a new UIViewController sub-class.

    a) In XCode, under Groups & Files,
        expand current project. Higfhlight Class, right
        click Add->New File... Refer to the
        diagram in the left.
       A new file selection menu will be poped up.
   b) In the new File windows, select UIViewController sub-class.
       Also select with XIB for users interface option. This option
       will generate the XIB file automatically. This XIB is to be used in 
       the interface builder, to simplify the creation of visual control in the
      UIView. If this option is not selected, the XIB file has to be created
      manually later after the class file is generated. This option will
      save two steps of manual work to create the XIB file.
     After that click on the Next button, to proceed to next step of the
     class generation.

  c) In the following new File window, specify the name for the
     UIViewController sub-class that to be created. After that click the
     finish button to generate the class, header and XIB files.
     * Note: As part of the programming convension the class name
        typically start with uppercase character and follow with lowercase
        characters.
    Uppercase first character is also usually used for all the following
    words in the class name.
    Eg. FirstView , SecondView

6. Once the UIViewController sub-class is being generated, the view can be customized according to
    the requirement in the interface builder by clicking the newly created XIB file. The UI control (eg.
    UISlider, UIButton, UILabel... etc) can be added to the view in interface builder.

7. To use the newly created UIViewController in the window application, it has to be pushed to the
    UINavigationController. The best way is to push through the didFinishedLaunchingWithOptions
    method in the applicationDelegate.m main class.  Eg: add the following code to
    didFinishedLaunchingWithOptions in ApplicationDelegate.m, assume that FirstView is newly
    created UIViewController:
                   FirstView *fv = [[UIViewController alloc] init];
                   fv.title = @"Title";  // To add a title to the UIViewController
                  [uiNavCtrl    pushViewController: fv animated: NO];
                  [fv  release];
    *Note: If the animated option is set to YES, the UIView will be shown in a animated way.
    Typically, if it is push through the didFinishedLaunchingWithOptions method, the animation will not show.

8. The newly created UIViewController can also be pushed through any UI controller such as UIButton ...
    etc. IBAction method can be used to push the UIViewController. Eg. The following code show how this
    can be done:
    a) Add IBAction in the FirstView.h
          -(IBAction) getSecondView: (id) sender;
    b) Add IBAction in the FirstView.m in the @interface section:
         -(IBAction) getSecondView: (id) sender  {
                 SecondView *sv = [[SecondView   alloc] init];
                 [self.navigationController   pushViewController: sv animated: YES];
                 [sv release];
         }
    c) Link the UI component change event to the above created IBAction.

Thursday, April 01, 2010

Modifying default UITextField behaviour - Iphone development

1. Create a cancel button in UITextField.
By default, the cancel button is disable when a new UITextField control is added to view. The button can be enabled by changing the option for Clear Button of the UITextField property.

Eg.



2. Disable the clearing old text in UITextField editing.
By default, when text is input to the UITextField, any previous entered text will be cleared. This can be disabled by unchecking the clear when editing begins option.
Eg.

Dismiss IPhone keyboard in text field control

By default, IPhone keyboard will not dismiss automatically after user click on the done button or touch other control or view. IPhone developer has to code this behaviour into the control.

The IPhone keyboard will only be dismissed after a resignFirstResponder message is send to the control.
Eg.
                 [textField resignFirstResponder];

There are probably many ways to add this message to the viewController code.  Below show two of them:

1. Implement  the textFieldShouldReturn delegate for the UITextField. Iphone will pass a message to textFieldShouldReturn method when the keyboard's done button is pressed. Call the send the resignFirstResponder message to the active UITextField will dismiss the keyboard. The following section outline the steps to accomplish this:

a)  Add to the viewController.h interface file to specify that it will implement the delegate textFieldShouldReturn method.
Eg.
@interface sampleViewController : UIViewController  
                                                    <UITextFieldDelegate>     
  // add this line to implement textFieldShouldReturn method, when more than one use comma

b) Implement the textFieldShouldReturn method in the .m implement file.
Eg.
-(BOOL)textFieldShouldReturn:(UITextField *)thisTextField  {
    [thisTextField resignFirstResponder];
    // add code to process the input if needed
    return TRUE;
}

c) link the textField to the class that implement the method.
Eg.


2. Override the touchesBegan method. Iphone will send the touchesBegan message when the view is being touched. In the overrided touchesBegan method, send the resignFirstResponder message to the active UITextField will dismiss the keyboard.
Example add the following code to the viewController:
- (void)touchesBegan:(NSSet *)touches withEvent: (UIEvent *)event {
    if( textField.editing) {   // UITextField.editing will return true if it is in the editing mode

       [textField resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];     // call the default touchesBegan method
}