Customize tableview cell - iphone

I am creating a customize UItableviewcell.
I have label and image(checkmark). On click of that image particular cell get checked, I did this for multiple selection, but now I want to select one cell at a time.
This is my code:
iphone
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
BOOL checkButtonPressed=FALSE;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UIImage *image = (checkButtonPressed) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
checkButton.frame = frame; // match the button's size with the image size
[checkButton setBackgroundImage:image forState:UIControlStateNormal];
[checkButton addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
//cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
for (int ii=0; ii<=[checkedArr count]; ii++) {
cell.textLabel.text =[dataArray objectAtIndex:ii];
}
//cell.backgroundColor = [UIColor clearColor];
cell.accessoryView = checkButton;
[cellArr addObject:cell];
[checkedArr addObject:[NSNumber numberWithBool:FALSE]];
return cell;
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:tableView];
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"val %d",[checkedArr count]);
if (indexPath != nil && iChecked == 0)
{
[self tableView:tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"in accessoryButtonTappedForRowWithIndexPath %d",indexPath.row);
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:!checked]];
UITableViewCell *cell = [cellArr objectAtIndex:indexPath.row];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
cell.accessoryView = button;
iChecked = 0;
}

Hi Friend You have to do like as below for single check mark..
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
if (curSelRowIndex == indexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;}
else {
cell.accessoryType = UITableViewCellAccessoryNone;}
return cell;
}
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
curSelRowIndex = indexPath.row;
[tblHistory reloadData];
}

Related

UITableViewCell shifts the content when reloaded

I am using a custom UITableViewCell with a UILabel at the top ,a UIButton just below the label and another UILabel,just under this button.
Final UILabel will be hidden initially,and will be opened when button action is called.The height of all the label and the cell are dynamic.
But
When i select the button ,the cell shifts its contentview to the.
center
I need the content of the cells to start at the origin itself.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ReferenceCell";
ReferenceiPadTableCell *cell = (ReferenceiPadTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ReferenceiPadTableCell" owner:self options:Nil];
cell = [nib objectAtIndex:0];
cell.accessoryView = nil;
}
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
NSDictionary *referenceDictionary = [self.referencesList objectAtIndex:indexPath.row];
NSString *nameString = [referenceDictionary objectForKey:#"name"];
CGSize labelSize = [nameString sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(listTableView.frame.size.width - 15, 125)
lineBreakMode:UILineBreakModeWordWrap];
labelSize.height = labelSize.height > 96? labelSize.height : 96;
cell.l1.text = nameString;
cell.l1.frame = CGRectMake(cell.l1.frame.origin.x, 6, cell.l1.frame.size.width, labelSize.height);
cell.button.tag = [[referenceDictionary objectForKey:#"sort"] intValue];
[cell.button addTarget:self action:#selector(showList:) forControlEvents:UIControlEventTouchUpInside];
cell.l2.hidden = YES;
cell.button.frame = CGRectMake(cell.button.frame.origin.x, cell.l1.frame.origin.y+ labelSize.height + 1, cell.l1.frame.size.width, cell.l1.frame.size.height);
if ([self.showList objectForKey:[NSString stringWithFormat:#"showList-%d", indexPath.row]] )
{
cell.l2.hidden = NO;
NSDictionary *dic = [self.abstractList objectAtIndex:indexPath.row];
NSString *abtString = [dic objectForKey:#"name"];
CGSize absSize = [abtString sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(tableView.frame.size.width - 15, 125)
lineBreakMode:UILineBreakModeWordWrap];
cell.l2.frame = CGRectMake(cell.button.frame.origin.x, cell.button.frame.origin.y+ cell.button.frame.size.height + 3, cell.button.frame.size.width, absSize.height);
cell.l2.text = abtString;
}
return cell;
}
it's doesn't shift the content but added more subview on UITableViewCell because you are not using reusing cell concept well.So use concept like this
-(UITableViewCell *)tableView:(UITableView *)tableView reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *) indexPath
{
UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
UILabel *lbl=[[UILabel alloc]init];
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
lbl.backgroundColor=[UIColor clearColor];
lbl.textAlignment=NSTextAlignmentCenter;
UIImageView *imgView=[[UIImageView alloc]init];
UIImageView *imgView1=[[UIImageView alloc]init];
UIImageView *imgView2=[[UIImageView alloc]init];
UIImageView *imgView3=[[UIImageView alloc]init];
UIImageView *imgView4=[[UIImageView alloc]init];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
{
lbl.font=[UIFont fontWithName:#"Marker Felt" size:20];
}
else
{
lbl.font=[UIFont fontWithName:#"Marker Felt" size:30];
}
[cell.contentView addSubview:lbl];
[cell.contentView addSubview:imgView];
[cell.contentView addSubview:imgView1];
[cell.contentView addSubview:imgView2];
[cell.contentView addSubview:imgView3];
[cell.contentView addSubview:imgView4];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[self tableView:tableView reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
}
}
}

How to show buttons in uitableview cell and their action will be shown on label on the same cell

In UITableViewCell there are different buttons and when I click on any button its action is being performed on all the cells, but I want that when I press the button then the action will be shown on the label of the same cell, I know I need to put them in array but how...?
when I click on the button one value is being incremented and it should be shown on the label of the same cell
here is the code:-
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
[cell addSubview:likeShow];
return cell;
}
This is the action of the button
-(void)likeFn{
NSString *str;
NSMutableString *mystring=[NSMutableString string];
likeCount++;
str =[NSString stringWithFormat:#"%d",likeCount];
NSString *world = #"Like";
NSString *helloWorld = [world stringByAppendingString:str];
likeShow.text=helloWorld;
}
Try the below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell-%d",indexPath.row];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//[cell clearsContextBeforeDrawing];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int lbltag = 1000;
UIButton *likeBtn = nil;
UILabel *likeShow = nil;
if ([cell viewWithTag:lbltag])
{
likeShow = (UILabel*)[cell viewWithTag:lbltag];
}
else
{
likeShow=[[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 20)] autorelease];
likeShow.text = [NSString stringWithFormat:#"%d likes",[[_marrTest objectAtIndex:indexPath.row] intValue]];
likeShow.tag = lbltag;
[cell addSubview:likeShow];
}
if ([cell viewWithTag:indexPath.row+1])
{
likeBtn = (UIButton*)[cell viewWithTag:indexPath.row+1];
}
else
{
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
likeBtn.tag = indexPath.row+1;
[likeBtn addTarget:self action:#selector(likeFn:) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(90, 0, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
}
return cell;
}
-(void)likeFn:(UIButton*)btnClicked
{
NSString *strLikes = [_marrTest objectAtIndex:btnClicked.tag-1];
int likeCount = [strLikes intValue] + 1;
[_marrTest replaceObjectAtIndex:btnClicked.tag-1 withObject:[NSString stringWithFormat:#"%d",likeCount]];
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:btnClicked.tag-1 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIndexPath];
UILabel *requiredLabel = (UILabel*)[cell viewWithTag:1000];
NSString *str = requiredLabel.text;
//str = [str stringByAppendingFormat:#"selected %#", str];
requiredLabel.text = #"";
requiredLabel.text = [NSString stringWithFormat:#"%d likes",[[_marrTest objectAtIndex:btnClicked.tag-1] intValue]];
//do what ever you want with the label
}
Create cell in separate nib file. add button and label for for that cell.
Also create a view class for that cell and set class for cell in nib file as class you created. Make outlet form nib to class file. Also create action for button and implement action. and use that cell in your table view.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn::) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.contentView addSubview:likeBtn];
[cell.contentView addSubview:likeShow];
return cell;
}
-(void)likeFn:(UIButton *)sender :(UIEvent *)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.view];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *str;
NSMutableString *mystring=[NSMutableString string];
likeCount++;
str =[NSString stringWithFormat:#"%d",likeCount];
NSString *world = #"Like";
NSString *helloWorld = [world stringByAppendingString:str];
for(id subView in cell.contentView.subviews){
{
if([subView isKindOfClass:[UILabel class]]){
UILabel *tmpLabel = (UILabel *)subView;
tmpLabel.text=helloWorld;
}
}
}
Try this code it may help you
try setting tags as:
likeBtn.tag = indexPath.row;
likeShow.tag = indexPath.row;
and in the likeFn:
- (void)likeFn: (id)sender {
UIButton * btn = (UIButton*)sender;
//check if the btn tag and label tag are same.
}
Check with this code.This may helpful for you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell clearsContextBeforeDrawing];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
[cell addSubview:likeShow];
return cell;
}
USE didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return;
}

iPhone : How can we load a custom check mark image for row in tableview?

I want to show a custom checkmark and uncheckmark image for tableview cell when user select any row and when a new row is inserted cell is loaded with uncheckmark image.
Once I check the row then even after reloading table with new data I want to display a previously checked row as it is and new as unchecked.
How can I get all rows with checked mark at end.
I tried but I am not able to load first time with custom checkmark image I can change when row is deselected but its also having some issues as it is not consistently working as I mentioned above.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cardData.mArrRecipient count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * sCellIdentifier = #"cell";
NSLog(#"cellforrow");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sCellIdentifier] autorelease];
RecipientData *recipientData = [[cardData.mArrRecipient objectAtIndex:indexPath.row]autorelease];
cell.textLabel.text = recipientData.sRecipientFName;
}
cell.accessoryType=UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (IndexPath)
{
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"img_checkmark_red.png"]] autorelease];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = imageView;
IndexPath=FALSE;
}
else
{
UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"img_uncheckmark_red.png"]] autorelease];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = imageView;
IndexPath=TRUE;
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([cardData.mArrRecipient count]>0)
{
[IBTblNewRecipientDetail reloadData];
}
}
can any one help me on this??
here is tutorial
http://weheartgames.com/2009/06/simple-iphone-checkbox/
or use this
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];
}
}
and
-(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];
}
}
For selecting multiple rows:
- (void)addTableView {
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake("whatever frame you want to set")
style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.timeSheetEntryTableView.allowsMultipleSelection = YES;
self.array = [[NSMutableArray alloc]init];
[self.view addSubview:self.tableView];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = #"Cell Identifier";
self.cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!self.cell) {
self.cell = [[Cell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
self.cell.accessoryType = UITableViewCellAccessoryNone;
}
self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ([self.array containsObject:indexPath])
{
[self.cell.checkImage setImage:[UIImage imageNamed:#"check_box_selected.png"]];
}
else
{
[self.cell.checkImage setImage:[UIImage imageNamed:#"check_box.png"]];
}
return self.cell;
}
//did select and deselect I have used custom cell
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.cell = [tableView cellForRowAtIndexPath:indexPath];
[self.array addObject:indexPath];
[self.cell.checkImage setImage:[UIImage imageNamed:#"check_box_selected.png"]];
}
- (void)tableView:(UITableView *)tableView
didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
self.cell = [tableView cellForRowAtIndexPath:indexPath];
[self.array removeObject:indexPath];
[self.cell.checkImage setImage:[UIImage imageNamed:#"check_box.png"]];
}

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;
}

How to obtain UITableViewCell in Accessory sample using Core Data

I have an application based on CoreDataBooks. I want to toggle two images in the cell accessory button as noted in the iOS sample code, but am running into a roadblock. I cannot figure out how to obtain the UITableViewCell that is noted in the accessoryButtonTappedForRowWithIndexPath: method. The sample stored the object in the item as key-value, but I cannot figure out how to do this with my patient and core data.
First of all, here is the relevant code from the Accessory sample:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"cell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame; // match the button's size with the image size
[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:event:) forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil)
{
[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
[item setObject:[NSNumber numberWithBool:!checked] forKey:#"checked"];
UITableViewCell *cell = [item objectForKey:#"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}
I am able to set my image correctly by using a "check" property of "Y" or "N" that I can store in CoreData, as noted below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Patient *patient = [fetchedResultsController_ objectAtIndexPath:indexPath];
cell.textLabel.text = patient.name;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
UIImage *image = [UIImage imageNamed:#"unchecked.png"];
if ([patient.check isEqualToString: #"Y"] == YES)
image = [UIImage imageNamed:#"checked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame; // match the button's size with the image size
[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:event:) forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
}
However, I am having problems with this method, as noted in the code:
- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
Patient *patient = [fetchedResultsController_ objectAtIndexPath:indexPath];
// HOW CAN I OBTAIN THE UITABLEVIEWCELL?
UITableViewCell *cell = [item objectForKey:#"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}
I appreciate any assistance.
AMENDMENT: Thanks to BoltClock, this all came together. Posting the final code in case anyone else wants to use this methodology.
- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Patient *patient = [fetchedResultsController_ objectAtIndexPath:indexPath];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *image = [UIImage imageNamed:#"checked.png"];
// patient.check is a string value set to either "Y" or "N"
// This allows the check mark to be permanently saved
if ([patient.check isEqualToString: #"Y"] == YES) {
image = [UIImage imageNamed:#"unchecked.png"];
patient.check = #"N";
}
else {
// image defaults to checked.png
// image = [UIImage imageNamed:#"checked.png"];
patient.check = #"Y";
}
[button setBackgroundImage:image forState:UIControlStateNormal];
// Save patient.check value
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Use the table view's cellForRowAtIndexPath: method and pass in the index path as the argument.
- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
Patient *patient = [fetchedResultsController_ objectAtIndexPath:indexPath];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}