0

I have an issue in an UITableView as I need to place a button on each row of the tableview and if i click the button, it gets selected at a time and selecting is like toggle. How to achieve this, please help me out to solve this problem.

Below is the following code that am trying to get it out. I am creating button on cellForRowAtIndexPath as shown below:

UIButton  *Btn = [[UIButton alloc]init];
Btn .frame = CGRectMake(3, 10, 33, 30);
[Btn setImage:[UIImage imageNamed:@"deselect.png"] forState:UIControlStateNormal];
[Btn addTarget:self action:@selector(method:) forControlEvents:UIControlEventTouchUpInside];
Btn.tag=indexPath.row;
[cell.contentView addSubview:Btn];

and the method: for button action:

-(void)method:(UIButton*)sender
{

     NSIndexPath  *indexpath1 = [NSIndexPath indexPathForRow:sender.tag inSection:0];

     Btn = (UIButton *)sender;

    //Btn.tag=sender.tag;
    [Btn setImage:[UIImage imageNamed:@"select.png"] forState:UIControlStateNormal];

}
1
  • 2
    What's the problem you're experiencing? What happens with the code that you've posted?
    – Caleb
    Jan 10, 2014 at 13:58

2 Answers 2

1

You have an array to store whether the button of a cell is selected or not. In the cellForRowAtIndexPath method, you should set 2 images for 2 states UIControlStateNormal and UIControlStateSelected of the button:

[Btn setImage:[UIImage imageNamed:@"select.png"] forState:UIControlStateSelected];
[Btn setImage:[UIImage imageNamed:@"deselect.png"] forState:UIControlStateNormal];

Then in the method: function, you switch the state of the button via Btn.selected based on the value in the array.

0
UIImage * btnLinkNormal = [UIImage imageNamed:@"select.png"];
[cell.linkButton setImage:btnLinkNormal forState:UIControlStateNormal];

// Add image to button for pressed state
UIImage * btnLinkHighlighted = [UIImage imageNamed:@"deselect.png"];
[cell.linkButton setImage:btnLinkHighlighted forState:UIControlStateHighlighted];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.