Friday, 20 January 2012

Radio Button in iPhone

Create Two Radio buttons with toggle action.


#define k1Tag 111
#define k2Tag 222


UIbutton *radioBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
radioBtn1=k1Tag;
[radioBtn1 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
[radioBtn1 setImage:[UIImage imageNamed:@"radio-on.png"] forState:UIControlStateSelected];
[radioBtn1 setFrame:YOUR_FRAME];
radioBtn1.selected=YES;

[radioBtn1 addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:radioBtn1];
UIButton *radioBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
radioBtn2.tag=k2Tag;
[radioBtn2 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
[radioBtn2 setImage:[UIImage imageNamed:@"radio-on.png"] forState:UIControlStateSelected];
[radioBtn2 setFrame:YOUR_FRAME];
[radioBtn2 addTarget:self action:@selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:radioBtn2];


//SELECTOR_ON_RADIO_BUTTONS

- (IBAction)checkboxButton:(UIButton *)button{
int tag = button.tag;
for (UIButton *radioBtn in [self.view subviews]) {
if ([radioBtn isKindOfClass:[UIButton class]] && ![radioBtn isEqual:button]) {
[radioBtn setSelected:NO];
}
}
if (!button.selected) {
button.selected = !button.selected;
}
if (tag == k1Tag) {
NSLog(@"YOUR_CODE_HERE_FOR_TAG_1");
}else if (tag == k2Tag) {
NSLog(@"YOUR_CODE_HERE_FOR_TAG_2");
}
}

No comments:

Post a Comment