how to check the condition for UIButtons in UITableview - ios

I am having three button image in table view, I want to check the conditions between them. when I click the button 1 means background image change to blue colour. at the same time I click the button 1 it will move to normal state white colour. Same for another two buttons.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath![button3 condition][3]
{
static NSString *cellIdentifier = #"HistoryCell";
CustomizedCellView *cell = (CustomizedCellView *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[CustomizedCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UIButton *button1;
button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = CGRectMake(80, 27, 36, 36);
[button1 setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"l"ofType:#"png"]] forState:UIControlStateNormal];
button1.tag = 1;
[button1 addTarget:self action:#selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
[button1 setSelected:true];
[cell.contentView addSubview:button1];
UIButton *button2;
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button2.frame = CGRectMake(160, 27, 36, 36);
[button2 setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"e"ofType:#"png"]] forState:UIControlStateNormal];
button2.tag = 1;
[button2 addTarget:self action:#selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
[button2 setSelected:true];
[cell.contentView addSubview:button2];
UIButton *button3;
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
button3.frame = CGRectMake(240, 27, 36, 36);
[button3 setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"v"ofType:#"png"]] forState:UIControlStateNormal];
button3.tag = 1;
[button3 addTarget:self action:#selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
[button3 setSelected:true];
[cell.contentView addSubview:button3];
return cell;
}
My condition is: when button 1 is clicked means button 3 should not change. when button 3 is clicked means button 1 should not change.button 2 can select in both the condition.
- (void)radiobtn:(UIButton *)button
{
if(button.tag == 1)
{
[button setImage:[UIImage imageNamed:#"lblue.png"] forState:UIControlStateSelected];
}
if(button.tag == 2)
{
[button setImage:[UIImage imageNamed:#"eblue.png"] forState:UIControlStateSelected];
}
if(button.tag == 3)
{
[button setImage:[UIImage imageNamed:#"vblue.png"] forState:UIControlStateSelected];
}
}
can any one help me in coding.

First of all you can set different tag for each button's like
button.tag == 1,
button.tag == 2,
button.tag == 3
And then after you can write your radiobtn Action like this way..
-(IBAction) radiobtn:(id)sender
{
UIButton *yourBtn = (UIButton *)[self.view viewWithTag:[sender tag]];
if(yourBtn.tag == 1) {
[yourBtn setImage:[UIImage imageNamed:#"lblue.png"] forState:UIControlStateSelected];
}
else if(yourBtn.tag == 2){
[yourBtn setImage:[UIImage imageNamed:#"eblue.png"] forState:UIControlStateSelected];
}
else{
[yourBtn setImage:[UIImage imageNamed:#"vblue.png"] forState:UIControlStateSelected];
}
}

button1.tag=1; button2.tag=2; button3.tag=3;
-(void)radiobtn:(UIButton *)button
{
if(button.tag==1)
{
if(![button3 isSelected])
{
if([button1 isSelected])
button1.backgroundColor = [UIColor blueColor];
else
button1.backgroundColor = [UIColor whiteColor];
}
else
{
//No change
}
}
else if(button.tag==2)
{
if([button2 isSelected])
button2.backgroundColor = [UIColor blueColor];
else
button2.backgroundColor = [UIColor whiteColor];
}
else if(button.tag==3)
{
if(![button1 isSelected])
{
if([button3 isSelected])
button3.backgroundColor = [UIColor blueColor];
else
button3.backgroundColor = [UIColor whiteColor];
}
else
{
//No change
}
}
}
Can you have a try on this..

Please check!! i have done same thing on my code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"UITableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
UIView * selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
[selectedBackgroundView setBackgroundColor:[UIColor redColor]]; // set color here
[cell setSelectedBackgroundView:selectedBackgroundView];
self.tableview.separatorColor = [UIColor whiteColor];
if (_userResult.relationStatus == [arrAnswrs objectAtIndex:indexPath.row]){
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else if (_userResult.childrenStatus == [arrAnswrs objectAtIndex:indexPath.row]){
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
else{
cell.accessoryType=UITableViewCellAccessoryNone;
}
[[UITableViewCell appearance] setTintColor:[UIColor redColor]];
cell.textLabel.text = [arrAnswrs objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Roboto" size:16];
cell.textLabel.textColor = UIColorFromRGB(0xe212121);
cell.backgroundColor = UIColorFromRGB(0xeaaea7);
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"Select indexPath.section %d --- index %d", (int)indexPath.section, (int)indexPath.row);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *status = [arrAnswrs objectAtIndex:indexPath.row];
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
int iSeletedButton = (int)selectButton.tag ;
NSLog(#"value %# -- iSeletedButton %d", [arrAnswrs objectAtIndex:indexPath.row], iSeletedButton);
switch (iSeletedButton) {
case 1:
_userResult.relationStatus = status;
_labelFrstStatus.text = status;
_labelFrstStatus.textColor = [UIColor blackColor];
break;
case 2:
_userResult.childrenStatus = status;
_labelSecndStatus.text = status;
_labelSecndStatus.textColor = [UIColor blackColor];
break;
default:
break;
}
if (_userResult.relationStatus || _userResult.childrenStatus) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
else cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView reloadData];
}

U can set tags to button
button1.tag=1;
button2.tag=2;
button3.tag=3; //instead of tag 1 for all buttons
Take reference for buttons as button1,button2,button3 globally..
NSLog(#"%#",[[sender superview] class]); //UITableViewCellContentView
NSLog(#"%#",[[[sender superview] superview] class]); //UITableViewCellScrollView
NSLog(#"%#",[[[[sender superview]superview]superview] class]); //UITableViewCell
- (void)radiobtn:(UIButton *)button
{
if(button.tag==1)
{
//handle
CustomizedCellView * cell = (CustomizedCellView*)[[[button superview]superview]superview];
if ([button.imageView.image isEqual:[UIImage imageNamed:#"lblue.png"]]) {
[button setImage:[UIImage imageNamed:#"lwhite.png"] forState:UIControlStateSelected];
}
for (UIButton *btn in cell.contentView.subviews) {
if (btn.tag==3) {
[btn setImage:[UIImage imageNamed:#"vwhite.png"] forState:UIControlStateSelected];
}
}
}
else if(button.tag==2)
{
//handle
if ([button.imageView.image isEqual:[UIImage imageNamed:#"eblue.png"]]) {
[button setImage:[UIImage imageNamed:#"ewhite.png"] forState:UIControlStateSelected];
}
}
else if(button.tag==3)
{
//handle
CustomizedCellView * cell = (CustomizedCellView*)[[[sender superview]superview]superview];
if ([button.imageView.image isEqual:[UIImage imageNamed:#"vblue.png"]]) {
[button setImage:[UIImage imageNamed:#"vwhite.png"] forState:UIControlStateSelected];
}
for (UIButton *btn in cell.contentView.subviews) {
if (btn.tag==2) {
[btn setImage:[UIImage imageNamed:#"lwhite.png"] forState:UIControlStateSelected];
}
}
}
}
Hope it helps you...!

Related

how to hide button on particular cell of tablview?

I want to hide button on some cell of UITableView , but I am not able to find what was I did wrong , some cell of my UITableView have both text and button and some cell have only text with single line or multiple line. I want to show button on some cell of UITableView. I did this code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellidentifier= #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier forIndexPath:indexPath];
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(5, 2, 100, 30);
[button setTitle:#"World" forState:UIControlStateNormal];
[button addTarget:self action:#selector(openNewPage:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
button.tag = indexPath.row;
[cell addSubview:button];
if(indexPath.row ==0)
{
cell.textLabel.attributedText = [dataArray objectAtIndex:0];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
if (indexPath.row == 1)
{
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:[dataArray objectAtIndex:1]] placeholderImage:nil];
cell.imageView.center = CGPointMake(cell.contentView.bounds.size.width/2,cell.contentView.bounds.size.height/2);
}
if(indexPath.row ==2)
{
cell.textLabel.attributedText = [dataArray objectAtIndex:2];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
if(indexPath.row ==3)
{
cell.textLabel.attributedText = [dataArray objectAtIndex:3];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
}
if(indexPath.row ==4)
{
cell.textLabel.attributedText = [dataArray objectAtIndex:4];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
}
if( indexPath.row == 5)
{
cell.textLabel.attributedText =[dataArray objectAtIndex:5];
cell.textLabel.textAlignment = NSTextAlignmentRight;
}
if(indexPath.row == 6)
{
//[button setHidden:YES];
cell.textLabel.attributedText = [dataArray objectAtIndex:6];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
}
if ( indexPath.row == 6 || indexPath.row == 5)
{
[button setHidden:NO];
}
else {
[button setHidden:YES];
}
return cell;
}
But this code will add button on 6th and 5th cell also on 2nd and 3rd cell also , I want button only 6th and 5th cell.
You shouldn't add a button as [cell addSubView: button] inside cellForRowAtIndexPath. dequeReusableCellForIndexPath asks the tableView for a cell. The tableView creates one if it doesn't have any or passes an old one. If you receive and old one, then I may already have a button. If you add another one, you will end up with a stack of buttons.
You can achieve what you want in two ways:
You can create your cell in the storyboard, for example, add the button and create an outlet in a subclass of UITableViewCell. Then you can hide or unhide the button according to what cell is.
The other way, if buttons are too different, you can create two cells in the storyboard with different identifiers, for example "cellWithButton" and "cellWithoutButton".
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
if (indexPath.row < 5) {
cell = [tableView dequeueReusableCellWithIdentifier:#"cellWithoutButton"];
} else {
cell = [tableView dequeueReusableCellWithIdentifier:#"cellWithButton"];
}
// Do the rest of your configuration
return cell;
}
I think You Should Try
adding button at start just add it later.
like,
if ( indexPath.row == 6 || indexPath.row == 5)
{
[cell addSubview:button];
}
else {
[button removeFromSuperview];
}
Simply you can do by
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];// or UIButtonTypeCustom
button.frame = CGRectMake(5, 2, 100, 30);
[button setTitle:#"World" forState:UIControlStateNormal];
[button addTarget:self action:#selector(openNewPage:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.textColor = [UIColor blueColor];
button.backgroundColor= [UIColor clearColor];
button.tag = indexPath.row;
[cell.contentView addSubview:button];
if(indexPath.row==0)
{
button.hidden = YES;
}
else if(indexPath.row==1){
button.hidden = YES;
}
else if(indexPath.row==2){
button.hidden = YES;
}
else if(indexPath.row==3){
button.hidden = YES;
}
else if(indexPath.row==4){
button.hidden = YES;
}
else if(indexPath.row==5 || indexPath.row==6){
button.hidden = NO;
}
OR else
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // or UIButtonTypeCustom
button.frame = CGRectMake(5, 2, 100, 30);
[button setTitle:#"World" forState:UIControlStateNormal];
[button addTarget:self action:#selector(openNewPage:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.textColor = [UIColor blueColor];
button.backgroundColor= [UIColor clearColor];
button.tag = indexPath.row;
if(indexPath.row==0)
{
}
else if(indexPath.row==1){
}
else if(indexPath.row==2){
}
else if(indexPath.row==3){
}
else if(indexPath.row==4){
}
else if(indexPath.row==5 || indexPath.row==6){
[cell.contentView addSubview:button];
}
Use this
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];// or UIButtonTypeCustom
button.frame = CGRectMake(5, 2, 100, 30);
[button setTitle:#"World" forState:UIControlStateNormal];
[button addTarget:self action:#selector(openNewPage:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.textColor = [UIColor blueColor];
button.backgroundColor= [UIColor clearColor];
button.tag = indexPath.row;
[cell.contentView addSubview:button];
if(indexPath.row==5 || indexPath.row==6){
button.hidden = NO;
}
else {
button.hidden = YES;
}
It will eliminate your code and readable too.
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(5, 2, 100, 30);
[button setTitle:#"World" forState:UIControlStateNormal];
[button addTarget:self action:#selector(openNewPage:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
button.tag = indexPath.row;
//add here
button.hidden==YES;
[cell addSubview:button];
and after write this condition
if ( indexPath.row == 6 || indexPath.row == 5)
{
[button setHidden:NO];
}
You should make [cell addSubview:button] in 6th and 5th cell

How to display checked images while scrolling the UITableView?

UITable view is working fine. when scrolling checked image is changed to uncheck. And also i need to take the particular checked image data in SAVE button Action.Can any body help me to solve this problem in prj.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal]; [cell addSubview:btn];
btn.tag=4;
forState:UIControlStateNormal];
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[sender setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateNormal];
} else {
[sender setImage:[UIImage imageNamed:#"unchecked.png"]forState:UIControlStateNormal];
}
}
Take one array which is Use to store IndexValue of Selected button,
#property (nonatomic,retain) NSMutableArray *arySelected;
Initialize array in ViewDidLoad,
- (void)viewDidLoad {
[super viewDidLoad];
self.arySelected = [[NSMutableArray alloc] init];
}
Change Code of TableViewCell Delegate,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
if (![arySelected containsObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]])
{
[btn setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateSelected];
}
else
{
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
}
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
// On your button Event,
-(void)checkBoxClicked:(id)sender
{
sender.selected = ! sender.selected;
if (sender.selected)
{
[arySelected addObject:[NSString stringWithFormat:#"%ld",(long)sender.tag]];
}
else
{
[arySelected removeObject:[NSString stringWithFormat:#"%ld",(long)sender.tag]];
}
[self.tableView reloadData];
}
you use the deferent state to set image like this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[sender setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateSelected];
btn.selected=NO;
btn.tag=4;
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
UIButton *tappedButton = (UIButton*)sender;
if (tappedButton.isSelected) {
tappedButton.selected=NO;
}
else
{
tappedButton.selected=YES;
}
}

Radio buttons get unselected while scrolling UITableView

I have two radio buttons on UITableView Cell.I am able to select one of them while scrolling UITableView down but when I scroll tableview up all radio buttons get unselected. After scrolling also I want to keep them selected but I am not able to do that....So please anyone having solution help me. Thank you
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
leftBtnclick.tag=999;
[leftBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[leftBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
if (screenHeight == 667)
{
[leftBtnclick setFrame:CGRectMake(50, 59, 30, 30)];
}
else if(screenHeight == 480)
{
[leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];
}
[leftBtnclick addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.leftOptBtn addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:leftBtnclick];
rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtnclick.tag=1000;
[rightBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[rightBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
if (screenHeight == 667)
{
[rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
}
else if(screenHeight == 480)
{
[leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];
}
[rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
[rightBtnclick addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.rightOptBtn addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:rightBtnclick];
cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
cell.questionLbl.text = [questionArray objectAtIndex:indexPath.row];
[cell.leftOptBtn setTitle:[leftOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell.rightOptBtn setTitle:[rightOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
return cell;
}
-(void)leftTickBtnClicked:(id)sender
{
UIButton *leftTickBtn=(UIButton *)sender;
leftTickBtn.selected=!leftTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==1000)
{
UIButton *rightTickBtn=(UIButton *)vw;
if(leftTickBtn.selected)
{
rightTickBtn.selected=NO;
}
else
{
rightTickBtn.selected=YES;
}
}
}
}
-(void)rightTickBtnClicked:(id)sender
{
UIButton *rightTickBtn=(UIButton *)sender;
rightTickBtn.selected=!rightTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==999)
{
UIButton *leftTickBtn=(UIButton *)vw;
if(rightTickBtn.selected)
{
leftTickBtn.selected=NO;
}
else
{
leftTickBtn.selected=YES;
}
}
}
}
You have created only one leftTickBtn and rightTickBtn and updated it each time when row is created. So finally whatever you have done with radio button, its affected to only last button.
Update your code as below :
UIButton *leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
leftBtnclick.tag=999+indexPath.row;
UIButton *rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtnclick.tag=1000+indexPath.row;
And implement methods like :
- (IBAction)leftTickBtnClicked:(UIButton *)sender
{
sender.selected = TRUE;
UITableViewCell *cell = [tblAppointment cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1000-sender.tag inSection:0]];
for (id view in cell.contentView.subviews)
{
if ([view isKindOfClass:[UIButton class]])
{
// your code
UIButton *btnRight = (UIButton *)view;
if (sender.selected == TRUE)
btnRight.selected = FALSE;
else
btnRight.selected = TRUE;
}
}
}
And
- (IBAction)rightTickBtnClicked:(UIButton *)sender
{
sender.selected = TRUE;
UITableViewCell *cell = [tblAppointment cellForRowAtIndexPath:[NSIndexPath indexPathForRow:999-sender.tag inSection:0]];
for (id view in cell.contentView.subviews)
{
if ([view isKindOfClass:[UIButton class]])
{
// your code
UIButton *btnLeft = (UIButton *)view;
if (sender.selected == TRUE)
btnLeft.selected = FALSE;
else
btnLeft.selected = TRUE;
}
}
}
You have this issue because of how the reusable cell works.
When you scroll away from the cell you made changes on the radio button , and then try to scroll back to that specific row ,a reusable cell dequeueReusableCellWithIdentifier does not guarantee that it will dequeue the exact same cell you made the changes and most likely it will dequeue a cell that you have not made any changes
You will need to keep track of the buttons selections in a List outside cellForRowAtIndexPath and reassign the selections to your radio buttons in cellForRowAtIndexPath much like the same idea with assigning the cell text every time with cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row]; by using the indexPath.row in an array
See modification [1] , [2] and [3] on the code below (haven't tested it but you get the idea)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
leftBtnclick.tag=999;
[leftBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[leftBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
if (screenHeight == 667)
{
[leftBtnclick setFrame:CGRectMake(50, 59, 30, 30)];
}
else if(screenHeight == 480)
{
[leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];
}
[leftBtnclick addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.leftOptBtn addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:leftBtnclick];
rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtnclick.tag=1000;
[rightBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[rightBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
if (screenHeight == 667)
{
[rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
}
else if(screenHeight == 480)
{
[leftBtnclick setFrame:CGRectMake(50, 40, 30, 30)];
}
[rightBtnclick setFrame:CGRectMake(180, 59, 30, 30)];
[rightBtnclick addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.rightOptBtn addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:rightBtnclick];
cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
cell.questionLbl.text = [questionArray objectAtIndex:indexPath.row];
[cell.leftOptBtn setTitle:[leftOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell.rightOptBtn setTitle:[rightOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
//[1]Set values for left and right
rightTickBtn.selected = [RightTicksArray objectAtIndex:indexPath.row];
leftTickBtn.selected = [LeftTicksArray objectAtIndex:indexPath.row];
return cell;
}
-(void)leftTickBtnClicked:(id)sender
{
UIButton *leftTickBtn=(UIButton *)sender;
leftTickBtn.selected=!leftTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==1000)
{
UIButton *rightTickBtn=(UIButton *)vw;
if(leftTickBtn.selected)
{
rightTickBtn.selected=NO;
}
else
{
rightTickBtn.selected=YES;
}
//[2]Update RightTickArray At Pos
[RightTickArray objectAtIndex:indexPath.row] = leftTickBtn.selected;
}
}
}
-(void)rightTickBtnClicked:(id)sender
{
UIButton *rightTickBtn=(UIButton *)sender;
rightTickBtn.selected=!rightTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==999)
{
UIButton *leftTickBtn=(UIButton *)vw;
if(rightTickBtn.selected)
{
leftTickBtn.selected=NO;
}
else
{
leftTickBtn.selected=YES;
}
//[3]Update LeftTickArray At Pos
[LeftTicksArray objectAtIndex:indexPath.row] = leftTickBtn.selected;
}
}
}
I got solution for my question. UITableView cells are reusable when you scroll tableview cell gets reused that's why radio button selection disappears. So solution is store your selection in one array use that array in cellForRowAtIndexPath. See code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
leftBtnclick.tag=999;
cell.leftOptBtn.tag=999;
[leftBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[leftBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
[leftBtnclick setFrame:CGRectMake(50, 59, 30, 30)];
[leftBtnclick addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.leftOptBtn addTarget:self action:#selector(leftBtnClicked) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:leftBtnclick];
rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
rightBtnclick.tag=1000;
cell.rightTickBtn.tag=1000;
[rightBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[rightBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
[rightBtnclick setFrame:CGRectMake(190, 59, 30, 30)];
[rightBtnclick addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.rightOptBtn addTarget:self action:#selector(rightBtnClicked) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:rightBtnclick];
cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
cell.questionLbl.text = [questionArray objectAtIndex:indexPath.row];
[cell.leftOptBtn setTitle:[leftOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell.rightOptBtn setTitle:[rightOptionArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
if ([[answerArray objectAtIndex:indexPath.row] isEqualToString:#"YES"])
{
leftBtnclick.selected=YES;
rightBtnclick.selected=NO;
}
else if ([[answerArray objectAtIndex:indexPath.row] isEqualToString:#"NO"])
{
leftBtnclick.selected=NO;
rightBtnclick.selected=YES;
}
else
{
leftBtnclick.selected=NO;
rightBtnclick.selected=NO;
}
return cell;
}
-(void)leftTickBtnClicked:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:questionTable];
NSIndexPath *indexPath1 = [questionTable indexPathForRowAtPoint:buttonPosition];
[answerArray replaceObjectAtIndex:indexPath1.row withObject:#"YES"];
UIButton *leftTickBtn=(UIButton *)sender;
leftTickBtn.selected=!leftTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==1000)
{
UIButton *rightTickBtn=(UIButton *)vw;
if(leftTickBtn.selected)
{
rightTickBtn.selected=NO;
}
else
{
rightTickBtn.selected=YES;
}
}
}
NSLog(#"Answer Array: %#",answerArray);
}
-(void)rightTickBtnClicked:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:questionTable];
NSIndexPath *indexPath1 = [questionTable indexPathForRowAtPoint:buttonPosition];
[answerArray replaceObjectAtIndex:indexPath1.row withObject:#"NO"];
UIButton *rightTickBtn=(UIButton *)sender;
rightTickBtn.selected=!rightTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==999)
{
UIButton *leftTickBtn=(UIButton *)vw;
if(rightTickBtn.selected)
{
leftTickBtn.selected=NO;
}
else
{
leftTickBtn.selected=YES;
}
}
}
NSLog(#"Answer Array: %#",answerArray);
}

How to create two radio buttons on a uitableview cell

I have created two radio buttons on one tableview cell.That are options for a question,But when I select them they both are get selected that I don't want,I want to select only one of them but I am not able to do that......Please help me Here is my code for customCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
leftBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
[leftBtnclick setTag:0];
[leftBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[leftBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
[leftBtnclick setFrame:CGRectMake(50, 120, 30, 30)];
[leftBtnclick addTarget:self action:#selector(leftTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:leftBtnclick];
rightBtnclick = [UIButton buttonWithType:UIButtonTypeCustom];
[leftBtnclick setTag:1];
[rightBtnclick setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[rightBtnclick setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateSelected];
[rightBtnclick setFrame:CGRectMake(180, 120, 30, 30)];
[rightBtnclick addTarget:self action:#selector(rightTickBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:rightBtnclick];
cell.numberLbl.text = [numberArray objectAtIndex:indexPath.row];
return cell;
}
-(void)leftTickBtnClicked:(id)sender
{
if ([leftBtnclick isSelected]) {
[sender setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
else
{
[sender setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
}
}
-(void)rightTickBtnClicked:(id)sender
{
if ([sender isSelected])
{
[sender setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
}
else
{
[sender setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
}
}
Firstly , set leftBtnclick.tag=999 and rightBtnclick.tag=1000.
And then add this code:-
-(void)leftTickBtnClicked:(id)sender
{
UIButton *leftTickBtn=(UIButton *)sender;
leftTickBtn.selected=!leftTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==1000)
{
UIButton *rightTickBtn=(UIButton *)vw;
if(leftTickBtn.selected)
{
rightTickBtn.selected=NO;
}
else
{
rightTickBtn.selected=YES;
}
}
}
}
-(void)rightTickBtnClicked:(id)sender
{
UIButton *rightTickBtn=(UIButton *)sender;
rightTickBtn.selected=!rightTickBtn.selected;
for(UIView *vw in [[sender superview]subviews])
{
if([vw isKindOfClass:[UIButton class]] && vw.tag==999)
{
UIButton *leftTickBtn=(UIButton *)vw;
if(rightTickBtn.selected)
{
leftTickBtn.selected=NO;
}
else
{
leftTickBtn.selected=YES;
}
}
}
}
Add four buttons on custom table cell IBOutlet it,and write this code in cellforrowatindexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TableIdentifier = #"CELL";
questionAireCell *cell = [questionAireTable dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil)
{
NSArray *obj = [[NSBundle mainBundle] loadNibNamed:#"questionAireCell" owner:self options:nil];
cell = [obj objectAtIndex:0];
}
cell.questionText.text=[cell.questionText.text stringByAppendingFormat:#"%ld",indexPath.row+1];
cell.commentText.userInteractionEnabled=YES;
cell.commentText.editable=YES;
cell.commentText.tag = indexPath.row;
cell.commentText.delegate = self;
NSLog(#"Question Count=%ld",questionDescriptionArr.count);
cell.questionText.text = [questionDescriptionArr objectAtIndex:indexPath.row];
NSString *number = [[[NSString alloc]initWithString:[srNumberArr objectAtIndex:indexPath.row]]stringByAppendingString:#"."];
cell.questionNoLbl.text = number;
[cell.rightOptBtn addTarget:self action:#selector(rightOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.rightTickBtn addTarget:self action:#selector(rightOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.leftOptBtn addTarget:self action:#selector(leftOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.leftTickBtn addTarget:self action:#selector(leftOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
// [cell.rightOptBtn addTarget:self action:#selector(rightOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
// [cell.rightTickBtn addTarget:self action:#selector(rightOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
// [cell.leftOptBtn addTarget:self action:#selector(leftOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
// [cell.leftTickBtn addTarget:self action:#selector(leftOptBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
if ([[answerArray objectAtIndex:indexPath.row] isEqualToString:#"YES"])
{
[cell.leftTickBtn setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
[cell.rightTickBtn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
}
else if ([[answerArray objectAtIndex:indexPath.row] isEqualToString:#"NO"])
{
[cell.leftTickBtn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[cell.rightTickBtn setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
}
else
{
[cell.leftTickBtn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[cell.rightTickBtn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
}
return cell;
}
-(void)leftOptBtnClicked:(UIButton *)sender
{
NSLog(#"Left btn clicked");
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:questionAireTable];
NSIndexPath *indexPath1 = [questionAireTable indexPathForRowAtPoint:buttonPosition];
[answerArray replaceObjectAtIndex:indexPath1.row withObject:#"YES"];
[questionAireTable reloadData];
NSLog(#"Answer Array: %#",answerArray);
}
-(void)rightOptBtnClicked:(UIButton *)sender
{
NSLog(#"Left btn clicked");
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:questionAireTable];
NSIndexPath *indexPath1 = [questionAireTable indexPathForRowAtPoint:buttonPosition];
[answerArray replaceObjectAtIndex:indexPath1.row withObject:#"NO"];
[questionAireTable reloadData];
NSLog(#"Answer Array: %#",answerArray);
}

Can not change image uibutton in uitableview after reloadData iOS

I create a tableview has button, this button has been changed image ass different condition. The first load tableview, these buttons set image correct but after condition change, it set image incorrect. Example : If [Selling = 0] , set image "Market.png", else [Selling =2], set image "MarketSelect.png". When value of Selling array changing, i used [_tableview reloadData] but it still not change image. I debug, i see MarketButton is 0x0000. The first load, MarketButton works correct but second load, it is 0x0000. Please give me advice to solve this problem. I tried 2 days but it can not works. thanks much
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.button.tag = indexPath.row;
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
market.tag = 4000;
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:market];
UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 30)];
pricelabel.backgroundColor = [UIColor clearColor];
pricelabel.font = [UIFont fontWithName:#"Helvetica" size:16];
pricelabel.font = [UIFont boldSystemFontOfSize:16];
pricelabel.textColor = [UIColor darkGrayColor];
pricelabel.tag = 3000;
//pricelabel.hidden = YES;
pricelabel.textAlignment = NSTextAlignmentRight;
[cell.contentView addSubview: pricelabel];
[pricelabel release];
}
UIButton *marketButton = (UIButton*)[cell.contentView viewWithTag:4000];
[marketButton setTag:indexPath.row];
if([sellingArray count]>0)
{
NSLog(#"sellingArray %#",sellingArray);
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]) // nothing
{
[marketButton setSelected:NO];
[marketButton setImage:[UIImage imageNamed:#"Marketplace.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
else if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"2"]) // marketplace
{
[marketButton setSelected:YES];
[marketButton setImage:[UIImage imageNamed:#"MarketplaceSelect.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
}
}
UILabel *pricelbl = (UILabel*)[cell.contentView viewWithTag:3000];
pricelbl.text =[NSString stringWithFormat:#"$%#",[priceNewArray objectAtIndex:indexPath.row]];
if ([sellingArray count]>0) {
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"2"]){
pricelbl.hidden = NO;
}
else if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]){
pricelbl.hidden = YES;
}
}
return cell;
}
marketpressAction :
- (void)marketPressedAction:(id)sender
{
buttonPressed = (UIButton *)sender;
buttontag = buttonPressed.tag;
NSLog(#"Market button click at row %d",buttontag);
}

Resources