Ruchi Raval
This user hasn't shared any biographical information
Homepage: http://www.mobisoftinfotech.com
Posts by Ruchi Raval
iPhone UITableView Tutorial: Grouped Table
May 11th
Grouped table view is an extension of the normal table view in iPhone. It displayes the data in several sectioned lists. Each section has a header and number of rows associated with it. Examples of grouped table are the ‘contacts’ list, a dictionary,etc. In this tutorial, we will create a grouped table using a dictionary, to create a names list,unlike the plain table in which we had used an array. So lets get started!
Step 1: Create a view based application and name it ‘GroupedTable’.
Step 2: Put the following code in ‘GroupedTableViewController.h’
#import <UIKit/UIKit.h>
@interface GroupedTableViewController : UIViewController {
NSDictionary *tableContents;
NSArray *sortedKeys;
}
@property (nonatomic,retain) NSDictionary *tableContents;
@property (nonatomic,retain) NSArray *sortedKeys;
@end
Here, we have declared a dictionary to hold the section headers and their respective row contents. And an array to hold the sorted keys of the dictionary.
Step 3: Now, open ‘GroupedTableViewController.m’ file and put the following code in it.
#import "GroupedTableViewController.h"
@implementation GroupedTableViewController
@synthesize tableContents;
@synthesize sortedKeys;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSArray *arrTemp1 = [[NSArray alloc]
initWithObjects:@"Andrew",@"Aubrey",@"Alice",nil];
NSArray *arrTemp2 = [[NSArray alloc]
initWithObjects:@"Bob",@"Bill",@"Bianca",nil];
NSArray *arrTemp3 = [[NSArray alloc]
initWithObjects:@"Candice",@"Clint",@"Chris",nil];
NSDictionary *temp =[[NSDictionary alloc]
initWithObjectsAndKeys:arrTemp1,@"A",arrTemp2,
@"B",arrTemp3,@"C",nil];
self.tableContents =temp;
[temp release];
self.sortedKeys =[[self.tableContents allKeys]
sortedArrayUsingSelector:@selector(compare:)];
[arrTemp1 release];
[arrTemp2 release];
[arrTemp3 release];
[super viewDidLoad];
}
- (void)dealloc {
[tableContents release];
[sortedKeys release];
[super dealloc];
}
#pragma mark Table Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.sortedKeys count];
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
return [self.sortedKeys objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)table
numberOfRowsInSection:(NSInteger)section {
NSArray *listData =[self.tableContents objectForKey:
[self.sortedKeys objectAtIndex:section]];
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
NSArray *listData =[self.tableContents objectForKey:
[self.sortedKeys objectAtIndex:[indexPath section]]];
UITableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
/*cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIdentifier] autorelease];
*/
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *listData =[self.tableContents objectForKey:
[self.sortedKeys objectAtIndex:[indexPath section]]];
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:rowValue];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"You selected"
message:message delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
viewdidLoad: Here, we populate the dictionary using three arrays of names as objects and alphabets as keys. Then we sort the array ‘allKeys’ of the dictionary and put it in sortedKeys.
Table Methods
numberOfSectionsInTableView : Returns the count of keys in the dictionary.
titleForHeaderInSection : Returns the value of key for that particular section.
cellForRowAtIndexPath : Here, listdata is an array which is assigned the value for the key corresponding to the respective section. For every section, the contents of listdata are displayed.
didSelectRowAtIndexPath : In this method, we display an alert view when a row is selected.
Step 4 : Open the ‘GroupedTableViewController.xib’. Drag and drop a table view on it. Select the table view and open its Attributes Inspector (command+1). Change the table style from ‘Plain’ to ‘Grouped’.
Step 5 : Open the Connections Inspector (command+2) for the table and link its datasource and delegate to the file’s owner.

Step 6 : You can download the source code here.Save,build and run the project. The output will be as follows:
iPhone UIButton tutorial: Radio Buttons
May 4th
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<([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<[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<[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<[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
Apr 30th
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:
iPhone Switch Control: UISwitch Control Tutorial
Feb 15th
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”.
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:
Thats the end of the tutorial folks. You are now ready to dabble with switches.
iPhone Segmented Control:UISegmentedControl Tutorial
Feb 13th
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.”
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:
Step 6: Open the Connections Inspector for segmented control and link the value changed argument to the segmentedControlIndexChanged method in the File’s Owner.
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.
OUTPUT:
Thats all folks! You are now ready to meddle with segmented control.















