iOS 5 - Change thumbnail of a table view cell on touch - ios5

So I'm trying to build here some kind of a to-do list - I have a table view, and on each cell I have a thumbnail which represents a checkbox. On touch, I want it to change images - from full to empty and vice versa. What I'm doing wrong? Here's some code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"taskCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 32, 32)];
[button addTarget:self action:#selector(checkmarkPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:#"checkbox_empty"] forState:UIControlStateNormal];
[button setTag:101];
[cell addSubview:button];
[cell setIndentationWidth:36];
[cell setIndentationLevel:1];
cell.textLabel.text = [[self.appDel.allTasks objectAtIndex:indexPath.row] taskName];
return cell;
}
- (void) checkmarkPressed:(UIButton *)sender{
if(sender.tag == 101){
UITableViewCell *cell = ((UITableViewCell*)[sender superview]);
NSLog(#"Cell %i", [self.tableView indexPathForCell:cell].row);
UIImage *empty = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"checkbox_empty" ofType:#"png"]];
UIImage *full = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"checkbox_full" ofType:#"png"]];
if ([sender imageView].image == [UIImage imageNamed:#"checkbox_empty"]) {
[sender setImage:full forState:UIControlStateNormal];
[self.tableView reloadData];
}
if ([sender imageView].image == full) {
[sender setImage:empty forState:UIControlStateNormal];
[self.tableView reloadData];
}
}
}

If you just want to change the image on touch , you can try this code
- (void) checkmarkPressed:(UIButton *)tempButton{
if (tempButton.tag == 101) {
tempButton.tag = 104;
[sender setImage:full forState:UIControlStateNormal];
}
else if (tempButton.tag == 104) {
tempButton.tag = 101;
[sender setImage:empty forState:UIControlStateNormal];
}
[self.tableView reloadData];
}

Found the solution :
if ([sender imageView].image == [UIImage imageNamed:#"checkbox_empty"]) {
[sender removeFromSuperview];
[sender setImage:full forState:UIControlStateNormal];
[[sender superview] addSubview:sender];
[self.tableView reloadData];
}
else if ([sender imageView].image == [UIImage imageNamed:#"checkbox_full"]) {
[sender removeFromSuperview];
[sender setImage:empty forState:UIControlStateNormal];
[[sender superview] addSubview:sender];
[self.tableView reloadData];
}

Related

how to detect the button touched on uitableViewCell and changed the BG image of that button

I'm implementing an application in which i have UIButton on every cell, this button adds particular event to user's favorite and clicking again on that image it removes that event from user's favorite. i want to detect on which cell user has pressed that button and want to change background image according to that.
Here is my code (what i've tried.)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
uncheckButton = [[UIButton alloc]init];
appDelegate.setValue = 0;
[uncheckButton setFrame:CGRectMake (3, 25, 30, 30)];
[uncheckButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[uncheckButton setSelected:NO];
[uncheckButton addTarget:self action:#selector(uncheckedButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:uncheckButton];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
-(IBAction)uncheckedButtonClicked:(id)sender
{
if(appDelegate.setValue ==0)
{
appDelegate.setValue =1;
[uncheckButton addTarget:self action:#selector(uncheckedButtonClicked:) forControlEvents: UIControlEventTouchUpInside];
[uncheckButton setFrame:CGRectMake(3, 25, 30, 30)];
[uncheckButton setImage:[UIImage imageNamed:#"checked_red.png"] forState:UIControlStateNormal];
Reachability *reachability = [Reachability reachabilityForInternetConnection] ;
NetworkStatus netWorkStatus = [reachability currentReachabilityStatus] ;
if (netWorkStatus == ReachableViaWWAN || netWorkStatus == ReachableViaWiFi)
{
[NSThread detachNewThreadSelector:#selector(threadStartAnimating:) toTarget:self withObject:nil];
NSLog(#"%#",appDelegate.user_id);
Communication *objCommunication = [[Communication alloc] init];
objCommunication.delegate = self;
[objCommunication setServiceFor:#"My_Agenda_add"];
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"%#/api/join_session",BASE_URL]];
NSString *body = [ NSString stringWithFormat:#"user_id=%#&session_id=%#",[appDelegate.user_id objectAtIndex:0],[[self.globalSessionArray valueForKey:#"_id"]valueForKey:#"$id"]];
[objCommunication makeAsynchronousRequestWithUrl:url withBodyString:body andWithMethod:#"POST"];objCommunication = nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:app_name message:network_connectivity delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
else if(appDelegate.setValue)
{
appDelegate.setValue = 0;
[uncheckButton addTarget:self action:#selector(uncheckedButtonClicked:) forControlEvents: UIControlEventTouchUpInside];
[uncheckButton setFrame:CGRectMake(3, 25, 30, 30)];
[uncheckButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
Reachability *reachability = [Reachability reachabilityForInternetConnection] ;
NetworkStatus netWorkStatus = [reachability currentReachabilityStatus] ;
if (netWorkStatus == ReachableViaWWAN || netWorkStatus == ReachableViaWiFi)
{
[NSThread detachNewThreadSelector:#selector(threadStartAnimating:) toTarget:self withObject:nil];
NSLog(#"%#",appDelegate.user_id);
Communication *objCommunication = [[Communication alloc] init];
objCommunication.delegate = self;
[objCommunication setServiceFor:#"My_Agenda_remove"];
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"%#/api/unjoin_session",BASE_URL]];
NSString *body = [ NSString stringWithFormat:#"user_id=%#&session_id=%#",[appDelegate.user_id objectAtIndex:0],[[self.globalSessionArray valueForKey:#"_id"]valueForKey:#"$id"]];
[objCommunication makeAsynchronousRequestWithUrl:url withBodyString:body andWithMethod:#"POST"];objCommunication = nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:app_name message:network_connectivity delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0] ;
NSLog(#"%#",indexPath);
UITableViewCell* cell = [self.agendaTableView cellForRowAtIndexPath:indexPath];
[cell addSubview:uncheckButton];
[self.agendaTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
The cleanest way to do this is creating a UITableViewCell subclass that handles the uncheckButtonClicked action. self will remain the target, and so it's always being handled by the correct cell.
Another option is to have an NSDictionary on the view controller level that keeps track of UIButton/UITableViewCell pairs. You can query the dictionary for the appropriate UITableViewCell that way.
Yet another option is to query the UIButton for it's superview, which will be the correct UITableViewCell.
-(IBAction)uncheckedButtonClicked:(id)sender
{
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)[button superview];
...
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyFeedCell";
NotificationCellView *cell = (NotificationCellView *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"NotificationCellView" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (NotificationCellView *)currentObject;
break;
}
}
}
zNotification *notifiItem=(zNotification *)[notificationData objectAtIndex:indexPath.row];
cell.Name.text = notifiItem.userName;
cell.clipImage.hidden= !notifiItem.hasFile;
[cell.clipImage addTarget:self action:#selector(viewFiles:) forControlEvents:
UIControlEventTouchUpInside];
cell.clipImage.tag=indexPath.row+100000;
cell.leftImg.hidden=YES;
cell.left.hidden=YES;
cell.centerImg.hidden=YES;
cell.center.hidden=YES;
//cell.right.hidden=YES;
//cell.rightImg.hidden=YES;
[cell.right addTarget:self action:#selector(wall_Followup:) forControlEvents:UIControlEventTouchUpInside];
cell.right.tag = 1100+indexPath.row;
if(notifiItem.Type==0)
{
[cell.right setTitle:#"Reply" forState:UIControlStateNormal];
}else
{
[cell.center setTitle:#"Followup" forState:UIControlStateNormal];
}
switch (notifiItem.Type) {
case 0:
cell.tag.text=#"New Followup";
[cell.userImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture",notifiItem.userImg]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
break;
case 1:
cell.tag.text=#"New Task";
[cell.userImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture",notifiItem.userImg]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.centerImg.hidden=NO;
cell.center.hidden=NO;
[cell.center setTitle:#"Done" forState:UIControlStateNormal];
[cell.centerImg setImage:[UIImage imageNamed:#"Done.png"]];
[cell.center addTarget:self action:#selector(doneTask:) forControlEvents:UIControlEventTouchUpInside];
cell.center.tag=1200+indexPath.row;
break;
case 2:
cell.tag.text=#"New Member";
[cell.userImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture",notifiItem.userImg]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
break;
case 3:
cell.tag.text=#"Task Reminder";
[cell.userImage setImage:[UIImage imageNamed:#"attention.png"]];
cell.Name.text = #"Attention";
cell.centerImg.hidden=NO;
cell.center.hidden=NO;
[cell.center setTitle:#"Done" forState:UIControlStateNormal];
[cell.centerImg setImage:[UIImage imageNamed:#"Done.png"]];
[cell.center addTarget:self action:#selector(doneTask:) forControlEvents:UIControlEventTouchUpInside];
cell.center.tag=1200+indexPath.row;
break;
case 4:
cell.tag.text=#"New File";
[cell.userImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://graph.facebook.com/%#/picture",notifiItem.userImg]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
break;
case 5:
cell.tag.text=#"Task Completed";
[cell.userImage setImage:[UIImage imageNamed:#"attention.png"]];
cell.Name.text = #"Attention";
cell.centerImg.hidden=NO;
cell.center.hidden=NO;
[cell.center setTitle:#"Delete" forState:UIControlStateNormal];
[cell.centerImg setImage:[UIImage imageNamed:#"Delete.png"]];
[cell.center addTarget:self action:#selector(deleteTask:) forControlEvents:UIControlEventTouchUpInside];
/*cell.leftImg.hidden=NO;
cell.left.hidden=NO;
[cell.left setTitle:#"Reassign" forState:UIControlStateNormal];
[cell.leftImg setImage:[UIImage imageNamed:#"re_Asign2.png"]];
[cell.left addTarget:self action:#selector(reAssign:) forControlEvents:UIControlEventTouchUpInside];*/
break;
case 6:
cell.tag.text=#"Task Deleted";
[cell.userImage setImage:[UIImage imageNamed:#"attention.png"]];
cell.Name.text = #"Attention";
break;
case 7:
cell.tag.text=#"Group Deleted";
[cell.userImage setImage:[UIImage imageNamed:#"attention.png"]];
cell.Name.text = #"Attention";
break;
case 8:
cell.tag.text=#"Group Invitation";
[cell.userImage setImage:[UIImage imageNamed:#"groupInv.png"]];
cell.Name.text = #"Invitation";
cell.centerImg.hidden=NO;
cell.center.hidden=NO;
[cell.center setTitle:#"Join" forState:UIControlStateNormal];
cell.center.tag = 1000+indexPath.row;
[cell.centerImg setImage:[UIImage imageNamed:#"join.png"]];
[cell.center addTarget:self action:#selector(joinGroup:) forControlEvents:UIControlEventTouchUpInside];
break;
default:
break;
}
cell.Details.text=notifiItem.MSG;
cell.date.text=notifiItem.date;//[NSString stringWithFormat:#"%d",notifiItem.Type];//notifiItem.date;
cell.groupName.text = notifiItem.group.title;
cell.accessoryType = UITableViewCellAccessoryNone;
if (!notifiItem.isChecked) {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
float whiteFloat[4] = {1.0, 0.7, 0.7, 1.0};
CGColorRef white = CGColorCreate(colorSpace, whiteFloat);
cell.detailBox.layer.shadowColor=[[UIColor redColor] CGColor];
cell.shade.layer.backgroundColor=white;
}else
{
//CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//float whiteFloat[4] = {0.7, 0.7, 0.7, 1.0};
//CGColorRef white = CGColorCreate(colorSpace, whiteFloat);
cell.detailBox.layer.shadowColor=[[UIColor blackColor] CGColor];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (IBAction)doneTask:(id)sender
{
UIButton *b=(UIButton *)sender;
NSLog(#"%d",b.tag);
[b setImage:[UIImage imageNamed:#"Delete.png"] forState:UIControlStateNormal];
zNotification *n=notificationData[b.tag-1200];
}
Hey
this is quick example from one of my projects
here is important case 3: code is complecated
but you can use tag of button to assign row number off cell 1200 i added b/c
there are more then one button in same cell so for button A 1200 and button B 1300 and when i call
function I remove 1200 or 1300 accordingly and doneTask function simply cast button to UIButton and get row number from tag and assign background image
There are several issues with this code:
You are adding a new button subview to the cell every time it is updated, which is causing a leak because you are not reusing the old button. Instead, you should add the button once in the initialization code only, and give it a tag that you can use to access the button when getting a reused cell.
Based on your description, you want to have both a checked and unchecked case but only seem to have one. To solve this you could have an if/else statement in cellForRowAtIndexPath that sets the image of the button to the correct one based on the model status.
hundredth's answer has a good suggestion which is to use some sort of model to keep track of which cell a button came from. An NSMutableDictionary would work well here. I would recommend against grabbing the superview of the button to get the cell it came from. Trying to get a model out of the view is bad practice and can lead to problems down the line.
Sample code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
UIButton *checkButton;
static const NSInteger kCheckButtonTag = 1;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
checkButton = [[UIButton alloc] init];
[checkButton setFrame:CGRectMake (3, 25, 30, 30)];
[checkButton addTarget:self action:#selector(checkedButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
checkButton.tag = kCheckButtonTag;
[cell.contentView addSubview:uncheckButton];
}
else
{
checkButton = (UIButton *)[cell.contentView viewWithTag:kCheckButtonTag];
}
if(model is unchecked) // replace with correct condition
[checkButton setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
else
[checkButton setImage:CHECKED_IMAGE_GOES_HERE forState:UIControlStateNormal]; // replace with your checked image
// assuming buttonToModelDictionary is an initialized ivar NSMutableDictionary
buttonToModelDictionary[checkButton] = YOUR_MODEL_OBJECT_GOES_HERE;
return cell;
}
- (void) checkButtonClicked:(id)sender
{
(UIButton *)button = (UIButton *)sender;
YOUR_MODEL_OBJECT_GOES_HERE = buttonToModelDictionary[button];
// do whatever you need to update the model here, then call [self.tableView reloadData] OR [self.tableView reloadRowsAtIndexPaths...] if you can gather the row using the model object, which you should be able to do.
}

How to save data of tableview cell

i am using custom checkbox buttons in my table view and want to save the selected cell's data to a mutable array.... can anyone help me... Thanks
create a mutable array to store your selected data, lets call it 'yourSeparatedData' , set the tag of your checkbox in cellForRowAtIndexPath and set onCheck: method as target. the code will look like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"setMe";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle………
}
checkBox = [UIButton buttonWithType:UIButtonTypeRoundedRect];
checkBox.frame = CGRectMake(customizeMe);
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:indexPath.row]] != NSNotFound)
{
[checkBox setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}
else {
[checkBox setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
}
[checkBox addTarget:self action:#selector(onCheck:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell addSubview:checkBox];
return cell;
}
-(void)onCheck:(id)sender {
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:[sender tag]]] != NSNotFound)
{
[sender setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
[yourSeparatedData removeObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
else {
[sender setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[yourSeparatedData addObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
[yourTableView reloadData];
}
this code is not tested, you are using checkbox so I assumed that you want to separate not just one data, at the end of the selection, you will have 'yourSeparatedData' with the objects picked from your tableView.
you can try custom action in UITableView cell for button prees,you can also use put a check box image and on click you can change the image as checked here is the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"identifire"];
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifire"] autorelease];
cell.detailTextLabel.text=[id_Array objectAtIndex:indexPath.row];
cell.detailTextLabel.hidden=YES;
button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"n_cross" ofType:#"png"];
UIImage *buttonImage1 = [[UIImage alloc] initWithContentsOfFile:path1];
[button setImage:buttonImage1 forState:UIControlStateNormal];
[button addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Custom Action" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0f, 20.0f, 40.0f, 40.0f);
[cell addSubview:button];
[buttonImage1 release];
CGRect imageFrame=CGRectMake(10,8,50,50);
self.cellimage=[[[UIImageView alloc] initWithFrame:imageFrame] autorelease];
self.cellimage.image=[imageIdArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:self.cellimage];
return cell;
}
-(void)customActionPressed :(id)sender
{
//Get the superview from this button which will be our cell
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *cell = [_tableView indexPathForCell:owningCell];
NSString *uid=[id_Array objectAtIndex:cell.row];
[id_Array removeObjectAtIndex:cell.row];
[_tableView reloadData];
[self performSelectorInBackground:#selector(ignoreRequest:) withObject:uid];
}
here i have an id_Array and on selection of a cell i just remove the object at that index
You have to do this manually, there is no facility in a UITableView or UITableViewController t o do this automatically.
When user selects any cell then in didSelectRowAtIndexPath you can add selected object dynamically.
[someMutableArr addObject:[tableArr objectAtIndex:indexPath.row]];
Try this
- (void)onButtonClick {
int numberOfSections = [tableView numberOfSections];
for (int section = 0; section < numberOfSections; section++) {
int numberOfRows = [tableView numberOfRowsInSection:section];
for (int row = 0; row < numberOfRows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
// Cell is selected
//here you can add that values into an array
} else {
// Cell is not selected
}
}
}
}

How to pass change the toggle button through indexpath of tableview in iPhone?

I have a tableview where I am displaying my values from database in tableview cells. In this tableview cellforrowatindexpath, I have created a button with an image on it and set selector for it. So when I click on the button my selector is called and it changes my image to another image.
But the problem is it does not identifies the indexpath i.e. if 4 rows are present in the tableview and if I click on the first row button, its image should change but problem is 4th row action is performed and its image is changed because it does not get the proper indexpath of the image to change.
This is my cellforrowatindexpath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d", indexPath.section, indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = 1;
onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
onButtonView.tag = 2;
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType::) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
This is my changemapType code
-(void)changeMapType:(NSIndexPath*)path1:(UIButton*)sender{
appDelegate.changeimagetype =!appDelegate.changeimagetype;
if(appDelegate.changeimagetype == YES)
{
onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = YES;
}
else
{
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = NO;
}
}
Don't break table view cell reuse just to put a different tag on each button. If your cells are the same, use the same reuse identifier.
You can find out the index path of the sender like this, without any need to mess around with tags. It also works for multi section tables.
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
I don't think you can have additional arguments in an #selector like that. What you might have to do is subclass UIButton and add an NSIndexPath property (or even just an int) and in -(void)changeMapType:(MyCustomButton*)sender access the property there.
Also it seems you do not even use the index path in changeMapType so that will need to be changed as well.
EDIT: Is it the button image you are trying to change? In which case you don't need the index path at all, or a subclass. Just use [sender setImage:(UIImage *)image forState:(UIControlState)state].
Use yourTableView for getting the Index Path.. Try something like this.
- (void)buttonAction:(UIButton*)sender {
UITableViewCell *cell = (UITableViewCell*)button.superview;
NSIndexPath *indexPath = [yourTableView indexPathForCell:cell];
NSLog(#"%d",indexPath.row)
}
I think following code might help you..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *myCheckbox = [[UIView alloc] init];
UIButton *myBt1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
if([appDelegate.changeimagetype == YES"]){
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}
else {
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
[myBt1 addTarget:self action:#selector(btcheckbox:) forControlEvents:UIControlEventTouchDown];
[myBt1 setTag:indexPath.row];
[myCheckbox addSubview:myBt1];
[myBt1 release];
[myCheckbox release];
[cell addsubview:myview];
return cell;
}
-(void) btcheckbox:(id) sender
{
UIButton *currentButton = (UIButton *) sender;
if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_OF.png"]])
{
appDelegate.changeimagetype = YES;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}else if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_ON.png"]])
{
appDelegate.changeimagetype = NO;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d", indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIButton *mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = indexPath.row;
//onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
//onButtonView.tag = 2;
// onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
mimageButton.selected = NO;
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)changeMapType:(UIButton*)sender{
if(sender.selected == YES)
{
// onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[sender setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
sender.selected = NO;
}
else
{
//onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[sender setImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
sender.selected = YES;
}
}

how to check uitableviewcell accessoryView contains image or not

Is it possible to check uitableviewcell accessoryview contains image or not?
For example
if([self.tableView cellForRowAtIndexPath:indexPath].accessoryView == [UIImage imageNamed:#"selected.png"] )
Some this like that or with different method.
Thank you
By default accessoryView will be null.
You can check for -
if (self.tableView.accessoryView) {
// An image is present
}
For my app I have created a custom cell and then added the imageView at the contentView
But for your requirement you can do something like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
cell.accessoryView = imageView];
imageView.tag = 3;
[imageView release];
}
NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
UIImageView *imageView;
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIImageView class]] && subview.tag == 3);
imageView = [subview copy];
}
[subviews release];
if([selectedArray containsObject:indexPath])
imageView.image = [UIImage imageNamed:#"Selected.png"];
else
imageView.image = [UIImage imageNamed:#"Unselected.png"];
}
And in this method do the same thing to get the imageView object
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
First:
if([self.tableView cellForRowAtIndexPath:indexPath].accessoryView == [UIImage imageNamed:#"selected.png"] )
this is wrong... acessaryview is not an image, it's UIView.
Check for:
if(nil != [self.tableView cellForRowAtIndexPath:indexPath].accessoryView)
{
// It has got something in it...
}
else
{
//create an accessary view....
}
This is how I implement multiselect tableview with checkboxes in each cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeCustom];
[disclosureButton setFont:[UIFont fontWithName:#"Arial-BoldMT" size:12.0]];
[disclosureButton setBackgroundImage:[UIImage imageNamed:#"checkboxoff.png"] forState:UIControlStateNormal];
disclosureButton.tag = 0;
[disclosureButton setFrame:CGRectMake(0,0, 30,30)];
[disclosureButton addTarget:self action:#selector(select:event:) forControlEvents:UIControlEventTouchUpInside];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.textLabel setUserInteractionEnabled:YES];
[cell setImage:[UIImage imageNamed:#"bluemappointer.png"]];
[cell setAccessoryView:disclosureButton];
}
else{
int n = indexPath.row;
if([selectedPlaces objectForKey:indexPath] != nil){
disclosureButton.tag = 1;
[disclosureButton setBackgroundImage:[UIImage imageNamed:#"checkboxon.png"] forState:UIControlStateNormal];
[cell setAccessoryView:disclosureButton];
}
else{
[disclosureButton setBackgroundImage:[UIImage imageNamed:#"checkboxoff.png"] forState:UIControlStateNormal];
disclosureButton.tag = 0;
[cell setAccessoryView:disclosureButton];
}
}
NSString *name = [tableData objectAtIndex:indexPath.row];
[cell.textLabel setText:name];
return cell;
}

Checkbox button in table view in iPhone

I want to create a check box in each row in in tableview. My code works for only one checkbox. If i have more than 1 it fails. My code is
UIButton * checkBox=[UIButton buttonWithType:UIButtonTypeCustom];
checkBox.tag=indexPath.row;
checkBox.frame=CGRectMake(270,15, 20, 20);
[cell.contentView addSubview:checkBox];
[checkBox setImage:[UIImage imageNamed:#"selectedBoxWith.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
-(void)checkBoxClicked:(id)sender{
if(self.isChecked ==NO){
self.isChecked =YES;
[sender setImage:[UIImage imageNamed: #"selectedBoxWithTik.png"] forState:UIControlStateNormal];
}else
{
self.isChecked =NO;
[sender setImage:[UIImage imageNamed:#"selectedBoxWith.png"]forState:UIControlStateNormal];
}
}
How can I handle it for more checkbox?
You just need to try this. It will work..........
-(void)checkBoxClicked:(id)sender{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"selectedBoxWith.png"]]) {
[sender setImage:[UIImage imageNamed: #"selectedBoxWithTik.png"] forState:UIControlStateNormal];
}
else {
[sender setImage:[UIImage imageNamed:#"selectedBoxWith.png"]forState:UIControlStateNormal];
}
}
You can not simply do this by using a simple UIButton as you will be needing to detect which row number checkbox was pressed. Hence instead of using a UIButton directly use a CustomButton which extends UIButton and has an extra property rowTag like:
#interface CustomButton : UIButton {
NSInteger rowTag;
}
#property NSInteger rowTag;
#end
#implementation CustomButton
#synthesize rowTag;
#end
Now in cellForRowAtIndexPath:
if(cell==nil){
CustomButton * checkBox=[CustomButton buttonWithType:UIButtonTypeCustom];
checkBox.tag=21;
checkBox.frame=CGRectMake(270,15, 20, 20);
[cell.contentView addSubview:checkBox];
[checkBox addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
}
CustomButton *btn = [cell.contentView viewWithTag:21];
[btn setRowTag:indexPath.row];
if(selectedProperty){
[checkBox setImage:[UIImage imageNamed:#"selectedBoxWithTik.png"] forState:UIControlStateNormal];
}
else
[checkBox setImage:[UIImage imageNamed:#"selectedBoxWith.png"] forState:UIControlStateNormal];
Hope this helps.
Example, click on first row is used to change for other rows. Click on other rows only change itself. arrCheckbox is an array used to store check of all rows.
- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(#"AV--%s", __func__);
HistoryCell2 *cell = [tableview dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
NSLog(#"Create new row");
[tableview registerNib:[UINib nibWithNibName:#"HistoryCell2" bundle:nil] forCellReuseIdentifier:CellId];
cell = [tableview dequeueReusableCellWithIdentifier:CellId];
}
cell.tag = indexPath.row;
BOOL checked = [[arrCheckbox objectAtIndex:indexPath.row] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"cb_on.png"] : [UIImage imageNamed:#"cb_off.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(1.0, 1.0, 29, 29);
button.frame = frame; // match the button's size with the image size
button.tag = indexPath.row;
[button setBackgroundImage:image forState:UIControlStateNormal];
// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
[button addTarget:self action:#selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
return cell;
}
- (void) checkButtonTapped:(id)sender
{
NSLog(#"%s", __func__);
UIButton *tappedButton = (UIButton*)sender;
int index = (int)tappedButton.tag;
NSLog(#"Row button: %d", index);
if(index > 0)
{
BOOL checked = [[arrCheckbox objectAtIndex:index] boolValue];
[arrCheckbox removeObjectAtIndex:index];
[arrCheckbox insertObject:(checked) ? #"0":#"1" atIndex:index];
UIImage *newImage = (checked) ? [UIImage imageNamed:#"cb_off.png"] : [UIImage imageNamed:#"cb_on.png"];
[tappedButton setBackgroundImage:newImage forState:UIControlStateNormal];
}
else{
//UITableView *tableview = (UITableView *)[[tappedButton superview] superview];
UIImage *newImage;
BOOL checked = [[arrCheckbox objectAtIndex:0] boolValue];
for(int i=0; i<[arrCheckbox count]; i++)
{
//NSLog(#"Row: %d------", i);
[arrCheckbox removeObjectAtIndex:i];
[arrCheckbox insertObject:(checked) ? #"0":#"1" atIndex:i];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
for(UIView *subview in cell.contentView.subviews)
{
if([subview isKindOfClass: [UIButton class]])
{
//NSLog(#"Modify button");
tappedButton = (UIButton*)subview;
//[subview removeFromSuperview];
newImage = (checked) ? [UIImage imageNamed:#"cb_off.png"] : [UIImage imageNamed:#"cb_on.png"];
[tappedButton setBackgroundImage:newImage forState:UIControlStateNormal];
}
}
}
}
}