Showing posts with label iphone tutorials. Show all posts
Showing posts with label iphone tutorials. Show all posts

IPhone tutorials UIText field Handling Keyboard Interactions

IPhone tutorials UIText field Handling Keyboard Interactions
This Tutorials 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 -
1 #import

2 @interface BackgroundTapForBlogViewController: UIViewController{
3 UITextField *tfUsername;
4 }
5 @property(nonatomic, retain) IBOutlet UITextField *tfUsername;
6 -(IBAction) textFieldDoneEditing : (id) sender;
7 -(IBAction) backgroundTap:(id) sender;
8 @end

BackgroundTapForBlogViewController.m file -
01 #import "BackgroundTapForBlogViewController.h"

02
03 @implementation BackgroundTapForBlogViewController
04 @synthesize tfUsername;
05
06 - (void)viewDidUnload {
07 self.tfUsername = nil;
08 }
09
10 - (void)dealloc {
11 [tfUsername release];
12 [super dealloc];
13 }
14
15 -(IBAction) textFieldDoneEditing : (id) sender{
16 [sender resignFirstResponder];
17 }
18
19 -(IBAction) backgroundTap:(id) sender{
20 [self.tfUsername resignFirstResponder];
21 }
22 @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.


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.
 
1 -(IBAction) backgroundTap:(id) sender{

2 [self.tfUsername resignFirstResponder];
3 }

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. 
 
 

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.
01 #import

02 #import "ScrollableViewController.h"
03 #import "MIBackgroundTapDelegate.h"
04
05 @interface BackgroundTapForBlogViewController:ScrollableViewController {
06 UITextField *tfUsername;
07 }
08 @property(nonatomic, retain) IBOutlet UITextField *tfUsername;
09 -(IBAction) textFieldDoneEditing : (id) sender;
10 //-(IBAction) backgroundTap:(id) sender;
11 @end
BackgroundTapForBlogViewController.m file-
01 #import "BackgroundTapForBlogViewController.h"

02
03 @implementation BackgroundTapForBlogViewController
04 @synthesize tfUsername;
05 - (void)viewDidLoad {
06 self.svScrollViewM.contentSize = CGSizeMake(320,416);
07 [self registerForEditingEvents:tfUsername];
08 [super viewDidLoad];
09 }
10
11 - (void)viewDidUnload {
12 self.tfusername = nil;
13 }
14 - (void)dealloc {
15 [tfUsername release];
16 [super dealloc];
17 }
18 -(IBAction) textFieldDoneEditing : (id) sender{
19 [sender resignFirstResponder];
20 }
21 -(IBAction) backgroundTap:(id) sender{
22 [self.tfUsername resignFirstResponder];
23 }
24 @end
25
26
27 MIBackgroundTapDelegate.h -
28 We declare a protocol for backgroundtap function.
29
30 [objc]
31 @protocol MIBackgroundTapDelegate
32 - (IBAction)backgroundTap:(id)sender;
33 @end
ScrollableViewController.h -

Declare properties and functions for the scroll view controller.
01 #import

02
03 @interface ScrollableViewController : UIViewController {
04 UIControl * ctrlKeyboardFocusFieldM;
05 BOOL bKeyboardShownM;
06 UIScrollView * svScrollViewM;
07 }
08
09 @property (nonatomic, retain) UIControl * ctrlKeyboardFocusFieldM;
10 @property (nonatomic, retain) IBOutlet UIScrollView * svScrollViewM;
11
12 - (void) registerForEditingEvents:(UIControl *) aControl;
13 - (void) registerForKeyboardNotifications;
14 - (void) keyboardWasHidden:(NSNotification*)aNotification;
15 - (void) keyboardWasShown:(NSNotification*)aNotification;
16 - (void) textFieldDidBeginEditing:(UITextField *)textField;
17 - (void) textFieldDidEndEditing:(UITextField *)textField;
18 @end
ScrollableViewController.m -
01 #import "ScrollableViewController.h"

02 @implementation ScrollableViewController
03 @synthesize ctrlKeyboardFocusFieldM;
04 @synthesize svScrollViewM;
05 - (void)viewDidLoad {
06 [self registerForKeyboardNotifications];
07 [super viewDidLoad];
08 }
09 - (void)didReceiveMemoryWarning {
10 // Releases the view if it doesn't have a superview.
11 [super didReceiveMemoryWarning];
12 }
13 - (void)viewDidUnload {
14 self.ctrlKeyboardFocusFieldM = nil;
15 self.svScrollViewM = nil;
16 }
17 - (void)dealloc {
18 [ctrlKeyboardFocusFieldM release];
19 [svScrollViewM release];
20 [super dealloc];
21 }
22 - (void)registerForKeyboardNotifications {
23 [[NSNotificationCenter defaultCenter] addObserver:self
24 selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
25 [[NSNotificationCenter defaultCenter] addObserver:self
26 selector:@selector(keyboardWasHidden:)
27 name:UIKeyboardDidHideNotification object:nil];
28 }
29
30 // Called when the UIKeyboardDidShowNotification is sent.
31 - (void)keyboardWasShown:(NSNotification*)aNotification{
32 if (bKeyboardShownM)
33 return;
34
35 NSDictionary* info = [aNotification userInfo];
36
37 // Get the size of the keyboard.
38 NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
39 CGSize keyboardSize = [aValue CGRectValue].size;
40
41 // Resize the scroll view (which is the root view of the window)
42 CGRect viewFrame = [self.svScrollViewM frame];
43 viewFrame.size.height -= keyboardSize.height;
44 self.svScrollViewM.frame = viewFrame;
45
46 // Scroll the active text field into view.
47 CGRect textFieldRect = [self.ctrlKeyboardFocusFieldM frame];
48 [self.svScrollViewM scrollRectToVisible:textFieldRect animated:YES];
49 bKeyboardShownM = YES;
50 }
51
52 // Called when the UIKeyboardDidHideNotification is sent
53 - (void)keyboardWasHidden:(NSNotification*)aNotification{
54 NSDictionary* info = [aNotification userInfo];
55
56 // Get the size of the keyboard.
57 NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
58 CGSize keyboardSize = [aValue CGRectValue].size;
59
60 // Reset the height of the scroll view to its original value
61 CGRect viewFrame = [self.svScrollViewM frame];
62 viewFrame.size.height += keyboardSize.height;
63 self.svScrollViewM.frame = viewFrame;
64 bKeyboardShownM = NO;
65 }
66
67 - (void)textFieldDidBeginEditing:(UITextField *)textField{
68 self.ctrlKeyboardFocusFieldM = textField;
69 }
70
71 - (void)textFieldDidEndEditing:(UITextField *)textField{
72 self.ctrlKeyboardFocusFieldM = nil;
73 }
74
75 - (void) registerForEditingEvents:(UIControl*)aControl{
76 [aControl addTarget:self action:@selector(textFieldDidBeginEditing:)
77 forControlEvents:UIControlEventEditingDidBegin];
78 [aControl addTarget:self action:@selector(textFieldDidEndEditing:)
79 forControlEvents:UIControlEventEditingDidEnd];
80 }
81 @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 -
1 #import

2 #import "MIBackgroundTapDelegate.h"
3
4 @interface MIScrollView : UIScrollView {
5 id backgroundTapDelegate;
6 }
7
8 @property (nonatomic, retain) idbackgroundTapDelegate;
9 @end
MIScrollView.m -
01 #import "MIScrollView.h"

02 #import "MIBackgroundTapDelegate.h"
03
04 @implementation MIScrollView
05 @synthesize backgroundTapDelegate;
06
07 -(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
08 if(backgroundTapDelegate) {
09 [backgroundTapDelegate backgroundTap: self];
10 }
11 }
12 @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.


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

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

You can download the source code from cinterviews here

Iphone Tutorials Grouped UI Table view

IPhone Tutorials Grouped UI Table view
 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’

01#import
02
03@interface GroupedTableViewController : UIViewController {
04  NSDictionary *tableContents;
05  NSArray *sortedKeys;
06}
07
08@property (nonatomic,retain) NSDictionary *tableContents;
09@property (nonatomic,retain) NSArray *sortedKeys;
10@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.

001#import "GroupedTableViewController.h"
002
003@implementation GroupedTableViewController
004@synthesize tableContents;
005@synthesize sortedKeys;
006
007// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
008- (void)viewDidLoad {
009  NSArray *arrTemp1 = [[NSArray alloc]
010   initWithObjects:@"Andrew",@"Aubrey",@"Alice",nil];
011  NSArray *arrTemp2 = [[NSArray alloc]
012   initWithObjects:@"Bob",@"Bill",@"Bianca",nil];
013  NSArray *arrTemp3 = [[NSArray alloc]
014    initWithObjects:@"Candice",@"Clint",@"Chris",nil];
015  NSDictionary *temp =[[NSDictionary alloc]
016    initWithObjectsAndKeys:arrTemp1,@"A",arrTemp2,
017    @"B",arrTemp3,@"C",nil];
018  self.tableContents =temp;
019  [temp release];
020  self.sortedKeys =[[self.tableContents allKeys]
021    sortedArrayUsingSelector:@selector(compare:)];
022  [arrTemp1 release];
023  [arrTemp2 release];
024  [arrTemp3 release];
025       [super viewDidLoad];
026}
027
028- (void)dealloc {
029  [tableContents release];
030  [sortedKeys release];
031        [super dealloc];
032}
033
034#pragma mark Table Methods
035
036- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
037    return [self.sortedKeys count];
038}
039
040- (NSString *)tableView:(UITableView *)tableView
041 titleForHeaderInSection:(NSInteger)section
042{
043  return [self.sortedKeys objectAtIndex:section];
044}
045
046- (NSInteger)tableView:(UITableView *)table
047numberOfRowsInSection:(NSInteger)section {
048  NSArray *listData =[self.tableContents objectForKey:
049            [self.sortedKeys objectAtIndex:section]];
050  return [listData count];
051}
052
053- (UITableViewCell *)tableView:(UITableView *)tableView
054     cellForRowAtIndexPath:(NSIndexPath *)indexPath {
055  static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
056
057  NSArray *listData =[self.tableContents objectForKey:
058      [self.sortedKeys objectAtIndex:[indexPath section]]];
059
060  UITableViewCell * cell = [tableView
061   dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
062
063  if(cell == nil) {
064
065     cell = [[[UITableViewCell alloc]
066     initWithStyle:UITableViewCellStyleDefault
067     reuseIdentifier:SimpleTableIdentifier] autorelease];
068
069    /*cell = [[[UITableViewCell alloc]
070         initWithStyle:UITableViewCellStyleSubtitle
071    reuseIdentifier:SimpleTableIdentifier] autorelease];
072    */
073  }
074
075  NSUInteger row = [indexPath row];
076  cell.textLabel.text = [listData objectAtIndex:row];
077
078  return cell;
079}
080
081- (void)tableView:(UITableView *)tableView
082didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
083  NSArray *listData =[self.tableContents objectForKey:
084   [self.sortedKeys objectAtIndex:[indexPath section]]];
085  NSUInteger row = [indexPath row];
086  NSString *rowValue = [listData objectAtIndex:row];
087
088  NSString *message = [[NSString alloc] initWithFormat:rowValue];
089  UIAlertView *alert = [[UIAlertView alloc]
090    initWithTitle:@"You selected"
091     message:message delegate:nil
092     cancelButtonTitle:@"OK"
093        otherButtonTitles:nil];
094  [alert show];
095  [alert release];
096  [message release];
097  [tableView deselectRowAtIndexPath:indexPath animated:YES];
098}
099
100@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 in cinterviews

Save,build and run the project. The output will be as follows:

Iphone Tutorials UITable view

Introduction to iPhone TableView
Table view is commonly used to show lists of data. A table view is the view object that displays table’s data and instance of UITableView. Each visible row in a table view is implemented by UITableViewCell. Table views are not responsible for storing your table’s data. They store only enough data to draw the rows that are currently visible. Table views get their configuration data from an object that conforms to the UITableViewDelegate protocol and their row data from an object that conforms to the UITableViewDataSource protocol.

Follow the steps below to create UITableView sample:
1.Open Xcode and CREATE VIEWBASED APP named simple table
2.Modify code in the SimpleTableViewController.h file as follow:

1 #import

2
3 @interface SimpleTableViewController : UIViewController
4 {
5 NSArray *listData;
6 }
7 @property(nonatomic, retain) NSArray *listData;
8 @end

3.Open SimpleTableViewController.xib file and drag Table View from Library over to the View Window.

4.Connect tableview’s dataSource and delegate from connection inspector to File’s Owner.
5.Modify code in the SimpleTableViewController.m file as follow:

01 #import "SimpleTableViewController.h"

02
03 @implementation SimpleTableViewController
04 @synthesize listData;
05
06 - (void)viewDidLoad {
07 NSArray *array = [[NSArray alloc] initWithObjects:@"iPhone", @"iPod",
08 @"iPad",nil];
09 self.listData = array;
10 [array release];
11 [super viewDidLoad];
12
13 }
14 - (void)dealloc {
15 [listData dealloc];
16 [super dealloc];
17 }
18
19 #pragma mark -
20 #pragma mark Table View Data Source Methods
21
22 - (NSInteger)tableView:(UITableView *)tableView
23 numberOfRowsInSection:(NSInteger)section
24 {
25 return [self.listData count];
26 }
27
28 - (UITableViewCell *)tableView:(UITableView *)tableView
29 cellForRowAtIndexPath:(NSIndexPath *)indexPath
30 {
31
32 static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
33 UITableViewCell *cell = [tableView
34 dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
35 if (cell == nil) {
36 cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
37 reuseIdentifier:SimpleTableIdentifier] autorelease];
38 }
39
40 NSUInteger row = [indexPath row];
41 cell.textLabel.text = [listData objectAtIndex:row];
42 return cell;
43
44 }
45 @end
In viewDidLoad we are creating an array of data to pass to our Table View.


We have also added two more methods of data source delegate which are mandatory to implement when your implementing UITableViewDataSource delegate.
 
1 (NSInteger)tableView:(UITableView *)tableView

2 numberOfRowsInSection:(NSInteger)section

which specifies how many number of rows are there in one section of the Table View.

The default number of section in Table View is one.
Another method is
1 - (UITableViewCell *)tableView:(UITableView *)tableView

2 cellForRowAtIndexPath:(NSIndexPath *)indexPath

Which is called by table view when it needs to draw a row. This method is called n times and value of n is equal to value returned by first method. As this method is called once for every row,


1 if (cell == nil)

checks, if cell exits before, if not create new cell. Here ‘indexPath’ parameter gives us current Indexpath of the row from which we can get the current drawing row. Then we set the text of textLabel property of the current drawing cell and finally return the cell to the Table View.


You can download the source code used in this tutorial from cinterviews.com here

Output will look like this:
        

IPhone Tutorial:Radio Buttons



IPhone 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.

01@interface MIRadioButtonGroup : UIView {
02NSMutableArray *radioButtons;
03}
04
05@property (nonatomic,retain) NSMutableArray *radioButtons;
06
07- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
08          andColumns:(int)columns;
09-(IBAction) radioButtonClicked:(UIButton *) sender;
10-(void) removeButtonAtIndex:(int)index;
11-(void) setSelected:(int) index;
12-(void)clearAll;
13@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.

001#import "MIRadioButtonGroup.h"
002
003@implementation MIRadioButtonGroup
004@synthesize radioButtons;
005
006- (id)initWithFrame:(CGRect)frame andOptions:(NSArray *)options
007  andColumns:(int)columns{
008
009  NSMutableArray *arrTemp =[[NSMutableArray alloc]init];
010  self.radioButtons =arrTemp;
011  [arrTemp release];
012   if (self = [super initWithFrame:frame]) {
013         // Initialization code
014     int framex =0;
015    framex= frame.size.width/columns;
016    int framey = 0;
017    framey =frame.size.height/([options count]/(columns));
018    int rem =[options count]%columns;
019    if(rem !=0){
020    framey =frame.size.height/(([options  count]
021    /columns)+1);
022}
023    int k = 0;
024   for(int i=0;i<([options count]/columns);i++){
025   for(int j=0;j
026
027  int x = framex*0.25;
028  int y = framey*0.25;
029  UIButton *btTemp = [[UIButton alloc]
030  initWithFrame:CGRectMake(framex*j+x, framey*i+y,
031  framex/2+x, framey/2+y)];
032  [btTemp addTarget:self action:
033  @selector(radioButtonClicked:)
034  forControlEvents:UIControlEventTouchUpInside];
035  btTemp.contentHorizontalAlignment =
036  UIControlContentHorizontalAlignmentLeft;
037  [btTemp setImage:[UIImage imageNamed:
038  @"radio-off.png"] forState:UIControlStateNormal];
039 [btTemp setTitleColor:[UIColor blackColor]
040  forState:UIControlStateNormal];
041  btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
042  [btTemp setTitle:[options objectAtIndex:k]
043  forState:UIControlStateNormal];
044 [self.radioButtons addObject:btTemp];
045 [self addSubview:btTemp];
046 [btTemp release];
047 k++;
048
049}
050}
051
052 for(int j=0;j
053
054int x = framex*0.25;
055int y = framey*0.25;
056UIButton *btTemp = [[UIButton   alloc]
057initWithFrame:CGRectMake(framex*j+x,
058framey* ([options count]/columns),
059framex/2+x,framey/2+y)];
060[btTemp addTarget:self action:@selector(radioButtonClicked:)
061forControlEvents:UIControlEventTouchUpInside];
062btTemp.contentHorizontalAlignment =
063UIControlContentHorizontalAlignmentLeft;
064[btTemp setImage:[UIImage imageNamed:@"radio-off.png"]
065forState:UIControlStateNormal];
066 [btTemp setTitleColor:[UIColor blackColor]
067 forState:UIControlStateNormal];
068 btTemp.titleLabel.font =[UIFont systemFontOfSize:14.f];
069 [btTemp setTitle:[options objectAtIndex:k]
070 forState:UIControlStateNormal];
071 [self.radioButtons addObject:btTemp];
072 [self addSubview:btTemp];
073 [btTemp release];
074 k++;
075
076 }
077
078 }
079 return self;
080}
081
082- (void)dealloc {
083  [radioButtons release];
084  [super dealloc];
085}
086
087-(IBAction) radioButtonClicked:(UIButton *) sender{
088
089 for(int i=0;i<[self.radioButtons count];i++){
090 [[self.radioButtons objectAtIndex:i] setImage:[UIImage
091 imageNamed:@"radio-off.png"]
092 forState:UIControlStateNormal];
093 }
094 [sender setImage:[UIImage imageNamed:@"radio-on.png"]
095 forState:UIControlStateNormal];
096
097}
098
099-(void) removeButtonAtIndex:(int)index{
100 [[self.radioButtons objectAtIndex:index] removeFromSuperview];
101}
102
103-(void) setSelected:(int) index{
104 for(int i=0;i<[self.radioButtons count];i++){
105 [[self.radioButtons objectAtIndex:i] setImage:[UIImage
106 imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
107
108 }
109 [[self.radioButtons objectAtIndex:index] setImage:[UIImage
110 imageNamed:@"radio-on.png"] forState:UIControlStateNormal];
111
112}
113
114-(void)clearAll{
115 for(int i=0;i<[self.radioButtons count];i++){
116 [[self.radioButtons objectAtIndex:i] setImage:[UIImage
117 imageNamed:@"radio-off.png"]
118                                                forState:UIControlStateNormal];
119 }
120}
121
122@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.


01#import "MIRadioButtonGroupAppDelegate.h"
02#import "MIRadioButtonGroup.h"
03
04@implementation MIRadioButtonGroupAppDelegate
05@synthesize window;
06
07- (void)applicationDidFinishLaunching:(UIApplication *)application {
08
09         // Override point for customization after application launch
10         NSArray *options =[[NSArray alloc]
11                        initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
12         MIRadioButtonGroup *group =[[MIRadioButtonGroup alloc]
13                                   initWithFrame:CGRectMake(0, 20, 320, 75)
14                                             andOptions:options andColumns:4];
15          [options release];
16          [window addSubview:group];
17          //[group setSelected:1];
18         //[group clearAll];
19        //[group removeButtonAtIndex:2];
20        [window makeKeyAndVisible];
21}
22
23- (void)dealloc {
24         [window release];
25         [super dealloc];
26}
27
28@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 from cinterviews.com here