iPhone – iPad

iPhone TabBar: UITabBarController Tutorial

A Tab Bar Controller helps to organize an application along functional lines.It is used to switch between multiple pages in an application. Each tab of a tab bar controller interface is associated with a view controller.Whenever a tab is tapped by a user,the tab bar controller object selects the particular tab and displays the corresponding view associated with the tab.This blog will assist you on how to create applications using tab bar controller.

Step 1 : Start Xcode and create a new project by selecting Window- Based Application.

Step 2 : Open “PrjTabBarControllerAppDelegate.h” and put following code in it.

#import <UIKit/UIKit.h>

@interface PrjTabBarControllerAppDelegate:NSObject
<UIApplicationDelegate> {

	   UIWindow *window;
	   UITabBarController *tcTabBar;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet *tcTabBar;
@end

Here ‘”tcTabBar” is an instance variable of type UITabBarController. We have created an outlet, so that we can relate our instance ‘tcTabBar’ with TabBarController.

Step 3 : Open “PrjTabBarControllerAppDelegate.m” and put following code in it. In the ‘applicationDidFinishLaunching’ method we have added the Tab Bar Controller as a sub view to the existing window. Save the project using (command + S).

#import "PrjTabBarControllerAppDelegate.h"

@implementation PrjTabBarControllerAppDelegate

@synthesize window;
@synthesize tcTabBar;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

	// Override point for customization after application launch
	[window addSubview:tcTabBar.view];
	[window makeKeyAndVisible];
}

- (void)dealloc {
	[tcTabBar release];
 	[window release];
  	[super dealloc];
}

@end

Step 4 : Open the Interface Builder by double clicking on MainWindow.xib file. Drag & Drop a Tab Bar Controller from the Library(shift + command + L.). Make sure that the Tab Bar Controller is dropped on the MainWindow.xib since it is not allowed to be placed on the View Controller.We will see a Tab Controller with two bar items created for us. Add one more tab item to it from the library.

As we can see a Tab Bar Item has ‘Title’ & ‘Image’ associated with it. Double Click on Item 1. Open the ‘Attributes Inspector’ (command + 1).In the ‘Atrributes Inspector’ we can set the title & image for Tab Bar Item. The image that we are adding should be present in the Project folder.To add an image to Project right click on ‘Resources’ -> Add -> Existing Files and select the image.

Step 5 : Now connect the Tab Bar Controller to PrjTabBarControllerAppDelegate. Open the ‘Connection Inspector’ (command + 2). Connect “tcTabBar” in the File’s Owner to Tab Bar Controller.

Step 6 : Right click on ‘Classes’ in Group & Files Explorer & add UIViewController subclass file. Select the option ‘With XIB for user interface’. The files added should be equal to number of Tab Bar items present.Here, we add three UIViewController so name them as View1ViewController, View2ViewController, View3ViewController.

Step 7 : Open the View2ViewController.xib by double clicking on it. Set the color of the view from the ‘Attribute Inspector’.Save & Close the .xib file. Similarly set the colours for other views.

Step 8 : Now we need to specify which views should be there in each tab of TabBarController. For this open ‘Interface Builder’. Open ‘Identity Inspector’ (command + 4). Set the class of each Tab Bar Item to its respective view.


Step 9 : Save,Build & Run the project.When we switch the tabs you will observe the views .

You can download the source code here.

Output:

iPhone UIButton tutorial: Radio Buttons

Radio buttons is a set of buttons out of which only one can be set at a time. For example: Selecting the time format out of 12-hr and 24-hr in a clock application.They are often required in iPhone UIs. Unfortunately, they are not included in the iPhone sdk. In this tutorial, we will learn how to create custom radio buttons.

Step 1: Create a window based application in Xcode and name it “MIRadioButtonGroup”.

Step 2: Create new “MIRadioButtonGroup.h” and “MIRadioButtonGroup.m” files which extend from UIView.
(Classes >> Add >> New File >> Objective C Class. Select UIView in the “subclass of” list.)

Step 3: Create a new group in the Classes folder and name it “MIRadioButtonGroup”. Drag the “MIRadioButtonGroup .h” and “MIRadioButtonGroup .m” files into the group.Now, add the images “radio-on.png” and “radio-off.png” to the group.

Step 4: Open the “MIRadioButtonGroup.h” file and make the following changes in it.

@interface MIRadioButtonGroup : UIView {
NSMutableArray *radioButtons;
}

@property (nonatomic,retain) NSMutableArray *radioButtons;

- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
          andColumns:(int)columns;
-(IBAction) radioButtonClicked:(UIButton *) sender;
-(void) removeButtonAtIndex:(int)index;
-(void) setSelected:(int) index;
-(void)clearAll;
@end

Here, we have declared a mutable array “radioButtons” which will hold all the buttons that we add to the radio button group.

The methods declared are:
initWithFrame – It is a constructor used to initialize the group. It takes the frame for the entire group,an array holding the titles of the buttons and the number of columns in which the buttons are to be arranged as input parameters.

radioButtonClicked – This method is used to set the button which is clicked.

removeButtonAtIndex – This method is used to remove a radio button at a particular index from the group.

setSelected – This method is used to set the button at the specified index.

clearAll – This method clears all the buttons including the currently set button.

Step 5: Open the “MIRadioButtonGroup.m” file and put the following code in it.

#import "MIRadioButtonGroup.h"

@implementation MIRadioButtonGroup
@synthesize radioButtons;

- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
      andColumns:(int)columns{

               NSMutableArray *arrTemp =[[NSMutableArray alloc]init];
               self.radioButtons =arrTemp;
               [arrTemp release];
              if (self = [super initWithFrame:frame]) {
                      // Initialization code
                      int framex =0;
                      framex= frame.size.width/columns;
                      int framey = 0;
                      framey =frame.size.height/([options count]/(columns));
                      int rem =[options count]%columns;
                      if(rem !=0){
                             framey =frame.size.height/(([options  count]
                                            /columns)+1);
            }
            int k = 0;
            for(int i=0;i&lt;([options count]/columns);i++){
                 for(int j=0;j<columns;j++){

                          int x = framex*0.25;
                          int y = framey*0.25;
                          UIButton *btTemp = [[UIButton alloc]
                           initWithFrame:CGRectMake(framex*j+x, framey*i+y,
                           framex/2+x, framey/2+y)];
                           [btTemp addTarget:self action:
                           @selector(radioButtonClicked:)
                            forControlEvents:UIControlEventTouchUpInside];
                            btTemp.contentHorizontalAlignment =
                             UIControlContentHorizontalAlignmentLeft;
                           [btTemp setImage:[UIImage imageNamed:
                           @"radio-off.png"] forState:UIControlStateNormal];
                           [btTemp setTitleColor:[UIColor blackColor]
                            forState:UIControlStateNormal];
                           btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
                         [btTemp setTitle:[options objectAtIndex:k]
                                 forState:UIControlStateNormal];
                         [self.radioButtons addObject:btTemp];
                         [self addSubview:btTemp];
                         [btTemp release];
                         k++;

               }
        }

        for(int j=0;j<rem;j++){

                int x = framex*0.25;
                int y = framey*0.25;
                UIButton *btTemp = [[UIButton   alloc]
                   initWithFrame:CGRectMake(framex*j+x,
                   framey* ([options count]/columns),
                                                framex/2+x,framey/2+y)];
                [btTemp addTarget:self action:@selector(radioButtonClicked:)
                   forControlEvents:UIControlEventTouchUpInside];
                btTemp.contentHorizontalAlignment =
                     UIControlContentHorizontalAlignmentLeft;
               [btTemp setImage:[UIImage imageNamed:@"radio-off.png"]
                                  forState:UIControlStateNormal];
               [btTemp setTitleColor:[UIColor blackColor]
                                    forState:UIControlStateNormal];
               btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
               [btTemp setTitle:[options objectAtIndex:k]
                                        forState:UIControlStateNormal];
               [self.radioButtons addObject:btTemp];
               [self addSubview:btTemp];
               [btTemp release];
               k++;

        }

    }
       return self;
}

- (void)dealloc {
         [radioButtons release];
         [super dealloc];
}

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

           for(int i=0;i&lt;[self.radioButtons count];i++){
                   [[self.radioButtons objectAtIndex:i] setImage:[UIImage
                               imageNamed:@"radio-off.png"]
                                    forState:UIControlStateNormal];
           }
           [sender setImage:[UIImage imageNamed:@"radio-on.png"]
                                 forState:UIControlStateNormal];

}

-(void) removeButtonAtIndex:(int)index{
           [[self.radioButtons objectAtIndex:index] removeFromSuperview];
}

-(void) setSelected:(int) index{
        for(int i=0;i&lt;[self.radioButtons count];i++){
             [[self.radioButtons objectAtIndex:i] setImage:[UIImage
           imageNamed:@"radio-off.png"] forState:UIControlStateNormal];

         }
         [[self.radioButtons objectAtIndex:index] setImage:[UIImage
          imageNamed:@"radio-on.png"] forState:UIControlStateNormal];

}

-(void)clearAll{
          for(int i=0;i&lt;[self.radioButtons count];i++){
                     [[self.radioButtons objectAtIndex:i] setImage:[UIImage
                                                 imageNamed:@"radio-off.png"]
                                                 forState:UIControlStateNormal];
            }
}

@end

initWithFrame – In this method, we first divide the frame into n number of boxes with width framex and height framey, where n =([options count]/columns)*columns. Then we check to see if there is any remainder for ([options count]/columns). The reason for this will be explained later.
In the proceeding nested “for” loops, we set the frames of the buttons so that each button occupies 50% space of each of the n boxes. After that we link the button programmatically to the “radioButtonClicked” method. We set the alignment of the content(radio button image and title) to left. Then we set the image for the button, configure its font color and font size and set its title.

This code works fine when the number of buttons is perfectly divisible by columns, but when it is not, the remaining buttons are not printed.
Now, the remainder comes in picture. What we do is, if there is a non-zero remainder, we add 1 to the divisor in framey equation,so that there is space for an extra row in the frame. In the next “for” loop, we insert that extra row and hence, cover the missing buttons.

radioButtonClicked – Here, we first clear all the buttons in the “radioButtons” array by setting their images to “radio-off.png”. Then, we set only the sender button by setting its image to “radio-off”.

removeButtonAtIndex – In this method, we remove the button at the specified index with the “removeFromSuperview” method.

setSelected – This method is similar to the “radioButtonClicked” method. The difference is we set the button at the specified index in the “radioButtons” array.

clearAll – In this method, we clear all the radio buttons by setting the images of the buttons in “radioButton” to “radio-off.png”.

Step 6: Now that we have created the “MIRadioButtonGroup” files, put the following code in the “MIRadioButtonGroupAppDelegate.m” file so that we can test them.

#import "MIRadioButtonGroupAppDelegate.h"
#import "MIRadioButtonGroup.h"

@implementation MIRadioButtonGroupAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

         // Override point for customization after application launch
         NSArray *options =[[NSArray alloc]
                        initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
         MIRadioButtonGroup *group =[[MIRadioButtonGroup alloc]
                                   initWithFrame:CGRectMake(0, 20, 320, 75)
                                             andOptions:options andColumns:4];
          [options release];
          [window addSubview:group];
          //[group setSelected:1];
         //[group clearAll];
        //[group removeButtonAtIndex:2];
        [window makeKeyAndVisible];
}

- (void)dealloc {
         [window release];
         [super dealloc];
}

@end

Step 7: Save, build and run the project. The output will be Output1. Now uncomment the commented lines one by one and observe the output. It will be Output 2, Output 3 and Output 1 respectively.

You can download the source code here.

iPhone UIButton tutorial : Custom Checkboxes

Checkbox is one of the elements that is frequently required in iPhone UIs, but the traditional checkbox is not present in iPhone sdk. Switches are sometimes used in the place of checkboxes.

In this tutorial, we will see how to create a custom checkbox. It extends from UIButton class. It is used to select or deselect a particular item or more than one items in a list. For example: The “Keep me signed in” checkbox in certain apps, sound on/off , effects on/off checkboxes in Settings of a gaming app.If more checkboxes are needed, we can create them similarly.

Step 1: Create a window based application in Xcode and name it “MICheckBox”.

Step 2: Create new “MICheckBox.h” and “MICheckBox.m” files which extend from UIView.

(Classes >> Add >> New File >> Objective C Class. Select UIView in the “subclass of” list.)

Step 3: Create a new group in the Classes folder and name it “MICheckBoxUtils”. Drag the “MICheckBox.h” and “MICheckBox.m” files into the group.Now, add the images “checkbox_not_ticked.png” and “checkbox_ticked.png” to the group.

Step 4: Open the “MICheckBox.h” file and make the following changes in it.

@interface MICheckBox : UIButton {
       BOOL isChecked;
}
@property (nonatomic,assign) BOOL isChecked;
-(IBAction) checkBoxClicked;

Here, we have changed the UIView class from which it extends to UIButton. Also, we have declared a boolean property “isChecked” which
keeps a track of whether the button is checked or not. “checkBoxClicked” is the method to change the state of checkbox when it is clicked.

Step 5: Now, open the “MICheckBox.m” file and add the following code to it.

#import "MICheckBox.h"

@implementation MICheckBox
@synthesize isChecked;

- (id)initWithFrame:(CGRect)frame {
              if (self = [super initWithFrame:frame]) {
                         // Initialization code

                         self.contentHorizontalAlignment =
                                    UIControlContentHorizontalAlignmentLeft;

                         [self setImage:[UIImage imageNamed:
                                     @"checkbox_not_ticked.png"]
                                     forState:UIControlStateNormal];

                          [self addTarget:self action:
                                     @selector(checkBoxClicked)
                              forControlEvents:UIControlEventTouchUpInside];
                }
                return self;
}

-(IBAction) checkBoxClicked{
               if(self.isChecked ==NO){
                        self.isChecked =YES;
                       [self setImage:[UIImage imageNamed:
                                    @"checkbox_ticked.png"]
                                    forState:UIControlStateNormal];

                }else{
                        self.isChecked =NO;
                        [self setImage:[UIImage imageNamed:
                                         @"checkbox_not_ticked.png"]
                                         forState:UIControlStateNormal];

                }
}

- (void)dealloc {
             [super dealloc];
}

@end

initWithFrame” method – This method initializes the button with the frame given by us. The contentHorizontalAlignment property allows us to set the alignment of the content (i.e image and text) of the button(checkbox). Initially, the image of the button will be the unselected checkbox, so we set the image “checkbox_not_ticked.png”. Then we programmatically link the button to the “checkBoxClicked” method.

“checkBoxClicked” method – In this method, whenever the checkbox is clicked, the image is changed from checked to unchecked and vice versa.

Step 6: Now that we have created the “MICheckBox” files, we need to test them. Hence, put the following code in the “MICheckBoxAppDelegate.m” file.

#import "MICheckBoxAppDelegate.h"
#import "MICheckBox.h"

@implementation MICheckBoxAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

             // Override point for customization after application launch
             MICheckBox *checkBox =[[MICheckBox alloc]
                          initWithFrame:CGRectMake(100, 200, 150, 25)];

             [checkBox setTitleColor:[UIColor blackColor]
                          forState:UIControlStateNormal];

             [checkBox setTitle:@"Checkbox"
                          forState:UIControlStateNormal];

             [window addSubview:checkBox];
             [window makeKeyAndVisible];
}

- (void)dealloc {
                 [window release];
                 [super dealloc];
}

@end

Here, we have imported the “MICheckBox.h” file so that we can create its instance. In the “applicationDidFinishLaunching” method, we create an object of MICheckbox and set its title color to black. Also, we set its title to CheckBox. Then we add the checkbox to the main window by the “addSubview” method.

Step 7: Download the source code for this tutorial here.
The output will be as follows:

CheckBox Unticked

CheckBox Ticked

iPhone Regular Expression Tutorial: RegexKitLite Framework

What is Regex ?

         Regex stands for Regular Expressions. It consists of constants and operators that denote sets of strings and operations over these sets, respectively. The definition is as follows :

Given a finite alphabet Σ, the following constants are defined:

Notation in Regular Expressions Meaning of the Notation
Empty Set
ε Empty String
a in Σ Character a in set Σ

 
A Regular Expression also supports operations like:

Operations Meaning of the Operation
RS denoting the set { αβ | α in R and β in S } 
e.g. R = {“a” , “b”} and S = {“c”,”d”} then RS = {“ac”,”ad”,”bc”,bd”}
Concatenation(can say, Cartesian Product )
R|S denoting the set R union S
e.g.R = {“a”,”b”} and s = {“a”,”c”} then R|S = {“a”,”b”,”c”}
Union
R* denoting the set as follows:
e.g. R = {“abc”, “d”} then R* = {ε,”abc”,”d”,”abcd”,”dabc”,……
Kleene Star

Here are some examples:

1.a | bc represents set of strings containing either a or bc in a string
2.(a | b)* represents set { ε ,a ,b , aa , bb , aaa , bbb ,….} 

         We can use these Regular Expressions in our iphone Program by using the RegexKitLite Class. So, lets get started with the RegexKitLite.

In this Blog, we are going to see :
     1.What is RegexKitLite ?
     2.Adding RegexKitLite to your Project.
     3.Use of RegexKitLite Framework(Example code).

What is RegexKitLite Framework?

          This Framework, basically provides a small set of extra methods for NSString class. These methods are to be used when regular expressions are to be used. We can use these methods in case of matching with range of strings with respect to the Regular Expression. In such a scenario, searching using substring can be extremely efficient.

Adding RegexKitLite to your Project:

   1.Download the source code of RegexKitLite from here.
   2.Browse these new files named “RegexKitLite.h” and “RegexKitLite.m” which were downloaded and add the same to your Project. This can be shown as below:

      Add -> Existing Files….

Note : Make Sure that “Copy items into Destination’s Group Folder(if needed)” option is checkmarked

   3.RegexKitLite uses the regular expression provided by the ICU library that ships with Mac OS X and since RegexKitLite uses the linker /usr/lib/libicucore.dylib ICU shared Library,we might get errors in our program within core Library files. To avoid this,please follow the steps below:

1.Go to Project -> Edit Project Settings

2.Type in linker in the search text and select the “Other Linker Flags” option.

3.Add a new linker flag named -licucore

Finally, we are done adding RegexKitLite to our Project.
Use of RegexKitLite Framework(Example code) :
          Since Regex adds methods to existing methods of NSString class, we are going to see some examples that can be executed using Regex. Now,Since the project has been setup in your application(WindowBasedApplication), just import the ”RegexKitLite.h” and add this code to your applicationDidFinishLaunching method.

- (void)applicationDidFinishLaunching:(UIApplication *)application {
//Extraction of valid mail ids
NSString * searchString = @" para.g@gmail.com sourabh_84368@gmail.com abc@def.in abcd@yahoomail.com mobisoft@mail.in andy@rediffmail.com";
NSString *regexString = @"[a-z0-9_.%]+@[a-z0-9_.%]+\\.[a-z][a-z][a-z]";
NSArray  *matchArray   = nil;
matchArray = [searchString componentsMatchedByRegex:regexString];
NSLog(@"matchArray: %@", matchArray);
// Override point for customization after application launch
[window makeKeyAndVisible];
}

Just run your application and check your console the output will be:

          Thus,we created an array which shown extracting strings which end with the character “g” from a main string. Similarly we can create many Regular Expressions use to extract the data that is required. For more information click here.

You can download the source code here.

iPhone FBConnect: Facebook Connect Tutorial

Please note that this tutorial is now obsolete. Please use facebook’s official tutorial

Now a days social networking websites like facebook are becoming very popular, so integrating facebook with app has become a necessity to make you application popular. We are going to do the same through this tutorial. The Facebook Connect SDK provides code which third-party developers can embed into their applications to connect to their Facebook accounts and exchange information with iPhone apps. It’s a way of embedding “social context” to an iPhone app, according to Facebook.

Create a Viewbased Application with name ‘FacebookAPI’.

Prerequisite:
1.Download Facebook Connect for iPhone SDK (http://svn.facebook.com/svnroot/platform/clients/packages/fbconnect-iphone.zip) or you can download same from here
Just go through the project. In particular, the “Connect” sample project. Sample Project gives demo of some of the functionality.

1.1.Open src/FBConnect.xcodeproj from SDK that you downloaded, and your own project as well.

1.2.Drag n drop FBConnect group. Make sure “Copy items into destination group folder” is NOT checked. It should look as shown below

1.3.Go to Project Menu ->Edit project settings and scroll down to “User Header Search Path” add entry which will point to “src folder”

1.4.To test import all .m n .h files in case any miss. And compile.

2.Login to Facebook. After that go to Developers Page (http://www.facebook.com/developers/) as shown below.

3.Register your application with Facebook

3.1.Click on Set up New Application Button in the upper right hand corner.

3.2.Give Application name and click on create application button. Then you will see new application screen with detail including “API key”and “API Secret Key”

Note : This application will not work until you provide your Facebook application’s API keys.

Now to get started with actual coding:

Append Following code in FacebookAPIAppDelegate.h

#import<UIKit/UIKit.h>
#import "FBConnect/FBConnect.h"
#import "FBConnect/FBSession.h"

@class FacebookAPIViewController;

@interface FacebookAPIAppDelegate : NSObject  {
          UIWindow *window;
          FacebookAPIViewController *viewController;
          FBSession *_session;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet
                           FacebookAPIViewController *viewController;
@property (nonatomic,retain) FBSession *_session;
@end

Append Following code in FacebookAPIAppDelegate.m

#import "FacebookAPIAppDelegate.h"
#import "FacebookAPIViewController.h"

@implementation FacebookAPIAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize _session;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}

- (void)dealloc {
          [_session release];
          [viewController release];
          [window release];
          [super dealloc];
}

@end

Here in FacebookAPIAppDelegate we have just declared _session variable of type FBSession to keep track of the session and to check if session for current user exists or not.

Append Following code in FacebookAPIViewController.h

#import <UIKit/UIKit.h>

#import "FBConnect/FBConnect.h"
#import "FBConnect/FBSession.h"

@interface FacebookAPIViewController : UIViewController   {
             FBLoginButton *loginButton;
             UIAlertView *facebookAlert;
             FBSession *usersession;
             NSString *username;
             BOOL post;
}

@property(nonatomic,retain) FBLoginButton *loginButton;
@property(nonatomic,retain)	UIAlertView *facebookAlert;
@property(nonatomic,retain)  FBSession *usersession;
@property(nonatomic,retain) NSString *username;
@property(nonatomic,assign) BOOL post;

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
-(void)getFacebookName;
-(void)postToWall;

@end

Append Following code in FacebookAPIViewController.m

#import "FacebookAPIViewController.h"
#import "FacebookAPIAppDelegate.h"

#define _APP_KEY @"Your API Key Goes here"
#define _SECRET_KEY @"Your Secrete Key Goes here"

@implementation FacebookAPIViewController
@synthesize loginButton;
@synthesize facebookAlert;
@synthesize usersession;
@synthesize username;
@synthesize post;

- (void)viewDidLoad {
               FacebookAPIAppDelegate *appDelegate =
                          (FacebookAPIAppDelegate *)   [[UIApplication
                                            sharedApplication]delegate];
                if (appDelegate._session == nil){
                appDelegate._session = [FBSession
                                   sessionForApplication:_APP_KEY
                                   secret:_SECRET_KEY delegate:self];
                 }
                 if(self.loginButton == NULL)
                 self.loginButton = [[[FBLoginButton alloc] init] autorelease];
                 loginButton.frame = CGRectMake(0, 0, 100, 50);
                 [self.view addSubview:loginButton];

                 [super viewDidLoad];
}

- (void)dealloc {
               [username release];
               [usersession release];
               [loginButton release];
               [super dealloc];
}

- (void)session:(FBSession*)session didLogin:(FBUID)uid {
                self.usersession =session;
                NSLog(@"User with id %lld logged in.", uid);
                [self getFacebookName];
}

- (void)getFacebookName {
         NSString* fql = [NSString stringWithFormat:
         @"select uid,name from user where uid == %lld",
                               self.usersession.uid];
        NSDictionary* params =
        [NSDictionary dictionaryWithObject:fql
        forKey:@"query"];
   [[FBRequest requestWithDelegate:self]
  call:@"facebook.fql.query" params:params];
   self.post=YES;
}

- (void)request:(FBRequest*)request didLoad:(id)result {
              if ([request.method isEqualToString:@"facebook.fql.query"]) {
                          NSArray* users = result;
                          NSDictionary* user = [users objectAtIndex:0];
                          NSString* name = [user objectForKey:@"name"];
                          self.username = name;

                          if (self.post) {
                                     [self postToWall];
                                     self.post = NO;
                          }
              }
}

- (void)postToWall {

               FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
                                             autorelease];
               dialog.userMessagePrompt = @"Enter your message:";
               dialog.attachment = [NSString
                    stringWithFormat:@"{\"name\":\"Facebook Connect for
                    iPhone\",\"href\":\"http://developers.facebook.com/
                    connect.phptab=iphone\",\"caption\":\"Caption\",
                    \"description\":\"Description\",\"media\":[{\"type\":
                    \"image\",\"src\":\"http://img40.yfrog.com/img40/
                     5914/iphoneconnectbtn.jpg\",\"href\":
                     \"http://developers.facebook.com/connect.php?
                      tab=iphone/\"}],\"properties\":{\"another link\":
                      {\"text\":\"Facebook home page\",\"href\":
                      \"http://www.facebook.com\"}}}"];

               [dialog show];

}

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

@end

Define API key and Secret key with the keys you received while registering your app on facebook.

#define _APP_KEY @"43e37a535cc09c2013bd76fde78dfcc7"
#define _SECRET_KEY @"cc14801521a0c4d1dc31b7cacb891072"

Validate session variable in ViewDidLoad. If it doesn’t exist then create the same for using API key and Secret key. For that, one needs to conform the protocol FBSessionDelegate in respective header file. Also create a login button using FBLoginButton.

While implementing protocol FBSessionDelegate one needs to implement following mandatory method

(void)session:(FBSession*)session didLogin:(FBUID)uid

This methos is automatically called when user is logged in using FBConnect SDK.
In this method we get session for that user and it’s uid which unique identifier for that user.

Once FBSession session is avaiable, we can accesss all the APIs provided by Facebook.
For now, we will see how to post user name and status on the facebook wall.

To get Facebook username a request is send in which select query is written to get username using uid.

NSString* fql = [NSString stringWithFormat:
@"select uid,name from user where uid == %lld", self.usersession.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];

Override following FBRequestDelegate method to check the reponse of above query.

(void)request:(FBRequest*)request didLoad:(id)result

The argument result is an array of NSDictionary Objects which contains info for that user as key-value pairs. Retrieve it as follows:

NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@"name"];

Use FBStreamDialog class post message on the facbook wall. A dialog pops up with a message box to post on Wall.

FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = @"Enter your message:";
dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"Facebook Connect for iPhone\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}"];
[dialog show];

Now Save project (Command +S). Build and Run Project.
Simulator will look like as follows

Click on Fconnect Button and Facebook Login Dialog will appear.

Login with your user name and Password . Wait for untill post to Wall Dialog pops up

The Msg on Facebook will something look like this

You can download the source code from here

iPhone UITextField Tutorial: Handling Keyboard Interactions

This post is written to provide you with the process to get the return button working on the keypad that pops up while filling a text field, the “Background Tap” functionality, and also what to do when the text field hides behind the keypad.

First we make a demo View-based Application for this, say “BackgroundTapForBlog” .
Add a text field to BackgroundTapForBlogViewController.xib, declare it in your BackgroundTapForBlogViewController.h file ,say tfUsername and link them in .xib.

Return Button on KeyPad:

Once you are done with this, add a function “textFieldDoneEditing” to the BackgroundTapForBlogViewController.m file, and do not forget to declare it in the BackgroundTapForBlogViewController.h file. This function gets rid of the keypad once you are done filling in the textfield.

BackgroundTapForBlogViewController.h file -

#import <UIKit/UIKit.h>
@interface BackgroundTapForBlogViewController: UIViewController{
UITextField *tfUsername;
}
@property(nonatomic, retain) IBOutlet UITextField *tfUsername;
-(IBAction) textFieldDoneEditing : (id) sender;
-(IBAction) backgroundTap:(id) sender;
@end

BackgroundTapForBlogViewController.m file -

#import "BackgroundTapForBlogViewController.h"

@implementation BackgroundTapForBlogViewController
@synthesize tfUsername;

- (void)viewDidUnload {
self.tfUsername = nil;
}

- (void)dealloc {
[tfUsername release];
[super dealloc];
}

-(IBAction) textFieldDoneEditing : (id) sender{
[sender resignFirstResponder];
}

-(IBAction) backgroundTap:(id) sender{
[self.tfUsername resignFirstResponder];
}
@end

Now, save your project (Command+S).
Finally, open BackgroundTapForBlogViewController.xib again and link the “textFieldDoneEditing” function from File’s Owner to your text field/fields, and select “DidEndOnExit” option.

Linking textFieldDoneEditing

Background Tap Functionality:

Other than the return button on the keypad, we do provide an option that the keypad should disappear if the user touches the background. This is done as follows -
Now go back to Xcode and declare a function “backgroundTap” in the BackgroundTapForBlogViewController.h file and add it to BackgroundTapForBlogViewController.m file.

-(IBAction) backgroundTap:(id) sender{
[self.tfUsername resignFirstResponder];
}

This function gets rid of the keypad. ResignFirstResponder notifies the receiver(in this case, tfUsername) that it is supposed to give up its status as first responder in the current window.
Save your project (Command+S).
Now, open BackgroundTapForBlogViewController.xib. Select UIView from the Main Window of Interface Builder and press Command+2 (open Connection Inspector). You will notice there is no option like touch up inside. So you need to change the class from UIView to UIControl in Identity Inspector (Command + 4). UIView is extended from UIControl, now events like touch up inside can be detected on a UIControl. Hence, this change.
Then select File’s Owner and link the function “backgroundTap” to the background of your view, and select option “Touch Up Inside” with UIControl.

Connecting backgroundTap function

Text Field Hiding behind keypad:

When the text field/fields begin hiding behind the keypad, it becomes necessary to scroll up so that the text field would be visible while filling it from the keypad.
For this, we need to include 5 files viz.,
MIBackgroundTapDelegate.h,
MIScrollView.h
MIScrollView.m
ScrollableViewController.h
ScrollableViewController.m

Add these files to your project, and follow the instructions -

BackgroundTapForBlogViewController.h –
Extend our controller from “ScrollableViewController”. We no longer need a declaration for backgroundTap function, since we are implementing MIBackgroundTapDelegate which has a declaration for the same.

#import <UIKit/UIKit.h>
#import "ScrollableViewController.h"
#import "MIBackgroundTapDelegate.h"

@interface BackgroundTapForBlogViewController:ScrollableViewController <MIBackgroundTapDelegate> {
UITextField *tfUsername;
}
@property(nonatomic, retain) IBOutlet UITextField *tfUsername;
-(IBAction) textFieldDoneEditing : (id) sender;
//-(IBAction) backgroundTap:(id) sender;
@end

BackgroundTapForBlogViewController.m file-

#import "BackgroundTapForBlogViewController.h"

@implementation BackgroundTapForBlogViewController
@synthesize tfUsername;
- (void)viewDidLoad {
self.svScrollViewM.contentSize = CGSizeMake(320,416);
[self registerForEditingEvents:tfUsername];
[super viewDidLoad];
}

- (void)viewDidUnload {
self.tfusername = nil;
}
- (void)dealloc {
[tfUsername release];
[super dealloc];
}
-(IBAction) textFieldDoneEditing : (id) sender{
[sender resignFirstResponder];
}
-(IBAction) backgroundTap:(id) sender{
[self.tfUsername resignFirstResponder];
}
@end
</objc>

<b>MIBackgroundTapDelegate.h -</b>
We declare a protocol for backgroundtap function.

[objc]
@protocol MIBackgroundTapDelegate
- (IBAction)backgroundTap:(id)sender;
@end

ScrollableViewController.h -
Declare properties and functions for the scroll view controller.

#import 

@interface ScrollableViewController : UIViewController {
UIControl * ctrlKeyboardFocusFieldM;
BOOL bKeyboardShownM;
UIScrollView * svScrollViewM;
}

@property (nonatomic, retain) UIControl * ctrlKeyboardFocusFieldM;
@property (nonatomic, retain) IBOutlet UIScrollView * svScrollViewM;

- (void) registerForEditingEvents:(UIControl *) aControl;
- (void) registerForKeyboardNotifications;
- (void) keyboardWasHidden:(NSNotification*)aNotification;
- (void) keyboardWasShown:(NSNotification*)aNotification;
- (void) textFieldDidBeginEditing:(UITextField *)textField;
- (void) textFieldDidEndEditing:(UITextField *)textField;
@end

ScrollableViewController.m -

#import "ScrollableViewController.h"
@implementation ScrollableViewController
@synthesize ctrlKeyboardFocusFieldM;
@synthesize svScrollViewM;
- (void)viewDidLoad {
[self registerForKeyboardNotifications];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
self.ctrlKeyboardFocusFieldM = nil;
self.svScrollViewM = nil;
}
- (void)dealloc {
[ctrlKeyboardFocusFieldM release];
[svScrollViewM release];
[super dealloc];
}
- (void)registerForKeyboardNotifications	{
[[NSNotificationCenter defaultCenter] addObserver:self
 selector:@selector(keyboardWasShown:)					 name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
 selector:@selector(keyboardWasHidden:)
 name:UIKeyboardDidHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification{
if (bKeyboardShownM)
return;

NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Resize the scroll view (which is the root view of the window)
CGRect viewFrame = [self.svScrollViewM frame];
viewFrame.size.height -= keyboardSize.height;
self.svScrollViewM.frame = viewFrame;

// Scroll the active text field into view.
CGRect textFieldRect = [self.ctrlKeyboardFocusFieldM frame];
[self.svScrollViewM scrollRectToVisible:textFieldRect animated:YES];
bKeyboardShownM = YES;
}

// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification{
NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Reset the height of the scroll view to its original value
CGRect viewFrame = [self.svScrollViewM frame];
viewFrame.size.height += keyboardSize.height;
self.svScrollViewM.frame = viewFrame;
bKeyboardShownM = NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
self.ctrlKeyboardFocusFieldM = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
self.ctrlKeyboardFocusFieldM = nil;
}

- (void) registerForEditingEvents:(UIControl*)aControl{
[aControl addTarget:self action:@selector(textFieldDidBeginEditing:)
forControlEvents:UIControlEventEditingDidBegin];
[aControl addTarget:self action:@selector(textFieldDidEndEditing:)
				forControlEvents:UIControlEventEditingDidEnd];
}
@end

1.registerForKeyboardNotifications function is used to set notifications whenever keyboard is shown or hidden, and it accordingly, calls selector methods keyboardWasShown or keyboardWasHidden respectively.
2.In keyboardWasShown function, we obtain the keyboard frame size, and resize it from the scroll view’s frame size (which is equivalent to shifting the scroll upwards).Accordingly, we also move the active text field to a location above the keyboard so as to make it visible.
3.In keyboardWasHidden function, we add the keyboard size to the current frame size, to obtain the original size, and it also move the active textfield to its original position.

MIScrollView.h -

#import
#import "MIBackgroundTapDelegate.h"

@interface MIScrollView : UIScrollView {
id backgroundTapDelegate;
}

@property (nonatomic, retain) idbackgroundTapDelegate;
@end

MIScrollView.m -

#import "MIScrollView.h"
#import "MIBackgroundTapDelegate.h"

@implementation MIScrollView
@synthesize backgroundTapDelegate;

-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
if(backgroundTapDelegate) {
[backgroundTapDelegate backgroundTap: self];
}
}
@end

In the BackgroundTapForBlogViewController.xib, add a scrollview, move everything on top of the scrollview and resize it as per requirement. In its Identity Inspector(Command+4), change its class to MIScrollView.
Link this scrollview to svScrollViewM of File’s Owner.

Linking scrollview

Link delegate and backgroundTapDelegate of MIScrollView to File’s Owner.

Linking Delegates of scrollview

Now, save your application in Xcode, and press Build & Go. When you select the textfield, the output would look like this -

Frame resized

You can download the source code from here.

iPhone Programming Tutorial: Event Handling

This blog is to familiarize you with the process of handling an event in an iPhone/iPod app.
We will create a demo project and walk you through the steps of handling an event, namely realizing a button click/touch on the iPhone/iPod screen.

Start Xcode and create a View based Application and name it “Event HandlingForBlog”.
To begin with, append EventHandlingForBlogViewController.h file

#import <UIKit/UIKit.h>
@interface EventHandlingForBlogViewController : UIViewController {
UIButton *btPrintM;
}
@property (nonatomic, retain) IBOutlet UIButton *btPrintM;

//This creates a property for your button declaring it as an outlet for use with view.

-(IBAction) printButtonPressed:(id) sender;
@end

printButtonPressed is the function to handle the event of user pressing the btPrintM button.

With this you’re done with the .h file.
Now, select the EventHandlingForBlogViewController.m file

#import "EventHandlingForBlogViewController.h"

@implementation EventHandlingForBlogViewController
@synthesize btPrintM;
- (void)viewDidUnload {
self.btPrintM = nil;
}
- (void)dealloc {
[btPrintM release];
[super dealloc];
}
-(IBAction) printButtonPressed : (id) sender{
NSLog(@"    Jai Ho");
}
@end

NSLog is like printf statement of C language. It prints onto the console.

Now, first save your project(Command+S).
Double-click on “EventHanldlingViewController.xib”.  This will launch the Interface Builder.

In the Interface Builder ‘s Library, scroll down to “Round Rect Button” and drag it onto your View Window at a suitable position.
Double-click inside the button you dragged to edit its text, to say Print “Jai Ho”.

Now to link this button with that declared in the  EventHanldlingForBlogViewController.h file, select the File Owner from Main Window and open its Connections Inspector(Command+2). Drag the “btPrintM” radio button from the connection inspector onto your button in View Window.

Linking Button


Now to link an event on your button to the function declared in   EventHanldlingForBlogViewController.h file, select the button and press Command+2 or launch the Inspector Window (Shift+Command+I) and select Connections Inspector (the second tab). Now drag from the radio button named “Touch Up Inside” to the “File’s Owner” in the Main Window of the Interface Builder.
Touch Up Inside refers to the action of user touching the iPhone screen in the area highlighted by your button.
You can also select Touch Drag Inside/Outside, Touch Down, Touch Down Repeat, etc.

A drop-down will appear. Select “printButtonPressed” from it

Connecting to method


Connecting to method


And thats it, you’ve completed your project. You can close the Interface Builder now and return to Xcode.
Now, save your project(Command+S).
To run this project,  click on the “Build & Go” button or (command + R).
The iPhone simulator will launch the application.

Output


Go ahead, click on the button. To check whether it printed or not, launch the console from Xcode. The console button is in the centre with “gdb” written over it, as shown below. Alternatively, you can select Run -> Console or press Shift+Command+R.

Console button


The console will display “Jai Ho”!!

Output on Console


You can download source code from here

iPhone Switch Control: UISwitch Control Tutorial

Switch in an iphone application is very similar to its electronic counterpart in its working. By default it is set to OFF. You can change its value manually or programmatically (as you prefer). When the switch is pressed, it toggles with animation and changes its state from ON to OFF or OFF to ON. For eg. It can be used to mute or unmute volume.

In this tutorial, we will change the value of the switch manually and programmatically. So lets get started.

Step 1: Start Xcode and create a view based application with name “SegmentedControlDemo”.

Step 2: Put the following code in “SwitchDemoViewController.h” file.

@interface SwitchDemoViewController : UIViewController {
		UILabel *switchLabel;
		UISwitch *toggleSwitch;
}

@property (nonatomic,retain) IBOutlet UILabel *switchLabel;
@property (nonatomic,retain) IBOutlet UISwitch *toggleSwitch;

-(IBAction) switchValueChanged;
-(IBAction) toggleButtonPressed;

@end

Put the following code in “SwitchDemoViewController.m” file.

@implementation SwitchDemoViewController
@synthesize switchLabel;
@synthesize toggleSwitch;

- (void)dealloc {
	[switchLabel release];
	[toggleSwitch release];
	[super dealloc];
}

-(IBAction) switchValueChanged{
	if (toggleSwitch.on) { switchLabel.text = @"Enabled"; }
	else { switchLabel.text = @"Disabled";}
}

-(IBAction) toggleButtonPressed{
	if(toggleSwitch.on){
		[toggleSwitch setOn:NO animated:YES];
	}
	else{
		[toggleSwitch setOn:YES animated:YES];

	}

}

@end

switchValueChanged method:
In this method, we have monitored the value of the switch. If it is on, we set the text of the label to “Enabled” and if it is off, we set it to “Disabled”.

toggleButtonPressed method:
Here, if the switch value is on, we set it to off using the setOn: animated: method. And vice versa.

Step 3: Save(command+s) the project. Open the “SwitchDemoViewController.xib” file from Resources folder. Add a label,switch and a button to the view.Name the button “toggle”.

SwitchDemoViewController.xib


Step 4: Now go to Connections Inspector(command+2) for File’s Owner. Connect switchLabel to label, toggleSwitch to switch, switchValueChanged method to “Value changed” event of the switch and toggleButtonPressed method to “Touch Up Inside” event of the button in the view.

Step 5: Save,build and run the project. When you toggle the switch, the text of the label will change and when you press the toggle button, the state of the switch will change.

You can download the source code here.

OUTPUT:

Output 1 for SwitchDemo


Output 2 for SwitchDemo

Thats the end of the tutorial folks. You are now ready to dabble with switches.

iPhone Slider Control: UISlider Control Tutorial

Slider is a horizontal bar with a slider button which can slide along the bar’s length. The value of the slider changes according to the position of the slider button and this value can be displayed on a label beside the slider. This is precisely what we are going to do in this tutorial.

Slider can be used as a value setter for a particular object such as a volume control.

Step 1: Start Xcode and create a view based application with name “SliderDemo”.

Step 2: Open “SliderDemoViewController.h” and put the following code in it.

 @interface SliderDemoViewController : UIViewController {
			UILabel *sliderLabel;

}

@property (nonatomic,retain) IBOutlet UILabel *sliderLabel;

-(IBAction) sliderChanged:(id) sender;

@end

Put the following code in the “SliderDemoViewController.m” file.

@implementation SliderDemoViewController
@synthesize sliderLabel;

- (void)dealloc {
	[sliderLabel release];
    	[super dealloc];
}

-(IBAction) sliderChanged:(id) sender{
	UISlider *slider = (UISlider *) sender;
	int progressAsInt =(int)(slider.value + 0.5f);
	NSString *newText =[[NSString alloc]
                  initWithFormat:@"%d",progressAsInt];
  self.sliderLabel.text = newText;
	[newText release];
}

@end

Here, in the sliderChanged method, we have declared an object of type slider. The variable progressAsInt has been used to store the slider’s position.0.5f is added to the slider value to round it off. We then put the value of progressAsInt in a string and set it as the label’s text.

Step 3: Save(command+s) the project. Now open the “SliderDemoViewController.xib” file from the Resources folder. Add a slider and a label beside it to the view as shown below.

SliderDemoViewController.xib


Open the Attributes Inspector for slider.Set the fields under Values as Minimum = 1,Maximum = 100 and Initial = 50.

Step 4: Open the Connections Inspector(command+2) for slider. Connect the value changed link to the sliderChanged method in File’s Owner. Also connect the label to sliderLabel in the File’s Owner.

Step 5: Save,build and run the project. Now as you slide the slider button, the value displayed by the label changes.

You can download the source code here.

OUTPUT:

Output for SliderDemo


Thats the end of the tutorial folks. You are now ready to dabble with your own version of slider.

iPhone Segmented Control:UISegmentedControl Tutorial

A segmented control shows a horizontal list of items. Each segment looks like a button. The segments remains “pressed” even after the user lifts his finger.When a different segment is tapped, its corresponding value can be obtained.
Segmented control comes in handy when you want to show/hide different data without changing the current view.For e.g you can have a set of images and you display only one when a segment is selected. When you select a different segment, depending on that, the picture changes.

So lets get started.:

Step 1:Start Xcode and create a view based application with name “SegmentedControlDemo”.

Step 2:Open the “SegmentedControlDemoViewController.h” file and put the following code in it.

#import <UIKit/UIKit.h>
@interface SegmentedControlDemoViewController : UIViewController {
UILabel *segmentLabel;
UISegmentedControl *segmentedControl;
}

@property (nonatomic,retain) IBOutlet UILabel *segmentLabel;
@property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;

-(IBAction) segmentedControlIndexChanged;

@end

Here, we have declared a label and segmented control and set properties and outlets for both of them.

Step 3:Open the “SegmentedControlDemoViewController.m” file. Synthesize both the properties and release them.Also provide the implementation for segmentedControlIndexChanged method.

#import "SegmentedControlDemoViewController.h"

@implementation SegmentedControlDemoViewController
@synthesize segmentLabel;
@synthesize segmentedControl;

// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
	self.segmentLabel.text =@"Segment 1 selected.";
	[super viewDidLoad];
}

- (void)dealloc {
	[segmentLabel release];
	[segmentedControl release];
	[super dealloc];
}

-(IBAction) segmentedControlIndexChanged{
	switch (self.segmentedControl.selectedSegmentIndex) {
		case 0:
			self.segmentLabel.text =@"Segment 1 selected.";
			break;
		case 1:
			self.segmentLabel.text =@"Segment 2 selected.";
			break;

		default:
			 break;
	 }

}

@end

In the segmentedControlIndexChanged method, we have used a switch case which switches the selected segment index of the segmented control. For each case, we have set the text of the label to the respective segment selected.

Step 4: Save(command+s) the project.Now open the “SegmentedControlDemoViewController.xib” file from the Resources folder. Drag and drop a label and a segmented control from the library on the view as shown below. Stretch the edges of the label so that it becomes long enough to display “Segment x selected.”

Xib after adding segmented control and label

Note: If you want more than two segments in the segmented control, go to Attributes Inspector for segmented control and change the value for Segments field.

Step 5:Select the File’s Owner in the xib window and open its Connections Inspector(command+2) and make the following connections.

Connect segmentControl to segmented control and segmentLabel to label. The Connections Inspector for File’s Owner will then look like this:

Connections

Step 6: Open the Connections Inspector for segmented control and link the value changed argument to the segmentedControlIndexChanged method in the File’s Owner.

Connection

Step 7: Build and run the project. You will see that when you tap different segments of the segmented control, the text of the label changes.

You can download the source code here.

OUTPUT:

Output1

Output2

Thats all folks! You are now ready to meddle with segmented control.