raja saran raja saran - 9 days ago 7
iOS Question

change the UIButton image in UITableView UIButton click

In UITableView

cellForRowAtIndexPath
create one button with one image. write action for that button click to change the button images. here the code.

ButtonImage = [UIImage imageNamed:@"work_exe_old.png"];
myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(250,10,34,34);
myButton.tag=22;
[myButton setBackgroundImage:ButtonImage forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(select_id:)forControlEvents:UIControlEventTouchDown];

- (IBAction)select_id:(id)search
{
UIButton *tempBtn =(UIButton *) search;
[tempBtn setImage:[UIImage imageNamed:@"work_exe.png"] forState:UIControlStateNormal];
}


clicked the button images changed(work_exe.png). wen click the same button again means the image want to change (work_exe_old.png) its like check box in tableview. how can i achieve tis

Answer

Instead of doing it in this way you can customise your code much better. Check the code below:

ButtonImage = [UIImage imageNamed:@"work_exe.png"];
ButtonImageSelected = [UIImage imageNamed:@"work_exe_old.png"];

myButton = [UIButton buttonWithType:UIButtonTypeCustom];

myButton.frame = CGRectMake(250,10,34,34);

myButton.tag=22;

[myButton setBackgroundImage:ButtonImage forState:UIControlStateNormal];

[myButton setBackgroundImage:ButtonImageSelected forState:UIControlStateSelected];

[myButton addTarget:self action:@selector(select_id:)forControlEvents:UIControlEventTouchDown];

And you can implement this selector method like this:

-(IBAction)select_id:(UIButton *) tempBtn {

  [tempBtn setSelected:! tempBtn.selected];
}