Reputation: 9
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];
}
Upvotes: 0
Views: 343
Reputation: 1
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];
Upvotes: 0
Reputation: 995
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.
Upvotes: 1