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

No comments: