UITableView didSelectRowAtIndexPath add additional checkmark at tap - iphone

When i select a player in 'didSelectRowAtIndexPath' and add a checkmark on the selected row it adds an additional checkmark.
If i tap row = 0 it adds a checkmark to row = 0 and row = 11. This means that two row's are marked by one tap. If i tap row = 1 it adds an extra checkmark to row = 10 so it adds checkmark 10 rows forward. It seems like it only add the checkmark as the player does not get into the actual player-list.
Any help would be very much appreciated.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(#"indexPath: %i", indexPath.row);
// To many players selected
if (nrOfSelectedPlayers == 6) { //This is max players allowed
UIAlertView *alertPlayer = [[UIAlertView alloc] initWithTitle:#"VARNING"
message:#"Du kan maximalt spela \n med sex spelare!"
delegate:self
cancelButtonTitle:#"Tillbaka"
otherButtonTitles:nil];
[alertPlayer show];
[alertPlayer release];
nrOfSelectedPlayers--;
checkDeletePlayer = YES;
}
else {
// Handle the number of selected players to be able to delete player +6
if (checkDeletePlayer == YES) {
checkDeletePlayer = NO;
nrOfSelectedPlayers++;
}
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[selectedPlayersArray addObject:cell.textLabel.text];
nrOfSelectedPlayers++;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
selectedPlayer = cell.textLabel.text;
for (int oo = 0; oo < nrOfSelectedPlayers; oo++) {
if ([selectedPlayersArray objectAtIndex:oo] == cell.textLabel.text) {
[selectedPlayersArray removeObjectAtIndex:oo];
nrOfSelectedPlayers--;
}
}
//nrOfSelectedPlayers--;
}
}
}

I am using storyboards with Dynamic Prototype Cells to display a list of states I used some of the ideas above before I found this solution
Step 1
#interface StateViewController : UITableViewController
{
NSMutableArray *checkedIndexPaths;
}
Step 2
(void)viewDidLoad
{
[super viewDidLoad];
self.states = [[GAIGStateStore sharedInstance]allStates];
//Setup default array to keep track of the checkmarks
checkedIndexPaths = [NSMutableArray arrayWithCapacity:self.states.count];
for (int i = 0; i < self.states.count; i++) {
[checkedIndexPaths addObject:[NSNumber numberWithBool:NO]];
}
}
Step 3
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//This toggles the checkmark
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//This sets the array
[checkedIndexPaths replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
} else
{
cell.accessoryType = UITableViewCellAccessoryNone;
//This sets the array
[checkedIndexPaths replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
}
}
Step 4
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:stateCell forIndexPath:indexPath];
UILabel *stateLabel = (UILabel *)[cell viewWithTag:1000];
StateProvince *myState = [self.states objectAtIndex:indexPath.row];
stateLabel.text = myState.label;
//Now set the check marks
// Assume cell not checked;
[cell setAccessoryType:UITableViewCellAccessoryNone];
NSNumber *num = [checkedIndexPaths objectAtIndex:indexPath.row];
if (num == [NSNumber numberWithBool:YES]) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
return cell;
}

The problem you are facing is caused by cell reusing.
Basically, if your UITableView has, let say 50 cells to display, it creates only 10 and then reuse them as you scroll down / scroll up. So whatever changes you did to the cell at row 0, it will be re-displayed for the row 11 as TableView uses the same cell etc.
What you want to do is to keep track of which players have been selected independently from cell. You can achieve that easily by creating a collection, let say NSMutableArray or NSMutableDictionary, which will store BOOL values in NSNumber objects, eg.
NSMutableArray *players = [NSMutableArray arrayWithCapacity:50];
for (int i = 0; i < 50; i++) {
[players addObject:[NSNumber numberWithBool:NO]];
}
Then in didSelectRowAtIndexPath:(NSIndexPath *)indexPath you do instead of operating on cell, you will simply change the value of a corresponding NSNumber object.
Then in cellForRowAtIndexPath:(NSIndexPath *)indexPath you configure cell accessory by checking the corresponding entry in players collection.
Or if you are really, really stubborn you could replace (THIS IS NOT RECOMENDED) the following line from the cellForRowAtIndexPath:(NSIndexPath *)indexPath:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
with:
UITableViewCell *cell = nil;

For others coming here (like I did) to see why their table selects random cells, you have to add something like the following to your cellForRowAtIndexPath:
// Assume cell not checked;
[cell setAccessoryType:UITableViewCellAccessoryNone];
for (int i = 0; i < checkedIndexPaths.count; i++) {
NSUInteger num = [[checkedIndexPaths objectAtIndex:i] row];
if (num == indexPath.row) {
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
}
I keep a NSMutableArray called checkedIndexPaths so that I know which indexPaths are checked. Keeping such an array allows you to easily limit the number of cells a user can check. Here's an example of my didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// uncheck if already checked
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
[checkedIndexPaths removeObject:indexPath];
}
else {
// make sure no more than 3 are selected
if ([checkedIndexPaths count] < 3) {
// check row
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// add it to our list of checked indexes
[checkedIndexPaths addObject:indexPath];
} else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Note"
message:#"You can only select 3 rows."
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Related

Changing the height of UITableViewCell on selection and deselection

I have a UITableView with cells , which on selected shows a popup with "Yes" or "No" confirmation ,When "Yes" is selected , the height of cell should be increased to 100 and its background image should change and if "No" is selected , nothing should happen and it should remain as a normal cell...
Similarly , if already selected cell is selected , again it shows up popup of "Yes" or "No" confirmation . If "Yes" is selected , the selected cell should convert into a normal cell with height 44 and background image is removed . If "No" is selected , then nothing happens and cell remains as a selected cell...
how to deal with height changes and background image changes in such condition ????
#import "TableViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
- (id)initWithStyleUITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
objects = [NSArray arrayWithObjects:#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",#" Ten",#"Eleven",#"Twelve",#"Thirteen", nil];
selectedIndexPath = [[NSIndexPath alloc] init];
}
return self;
}
- (NSInteger)numberOfSectionsInTableViewUITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section
{
// Return the number of rows in the section.
return [objects count];
}
- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseI dentifier:CellIdentifier];
cell.textLabel.text = [objects objectAtIndex:indexPath.row];
NSLog(#"cell description:- %#",[cell description]);
}
return cell;
}
- (CGFloat)tableViewUITableView *)tableView heightForRowAtIndexPathNSIndexPath *)indexPath
{
// if (indexPath == selectedIndexPath)
// {
// return 100 ;
// }
// if (indexPath == selectedIndexPath)
// {
// UITableViewCell *c = [self.tableView cellForRowAtIndexPath:indexPath];
// CGRect rect = c.frame ;
// rect.size.height = 100 ;
// c.frame = rect ;
// return 100;
// }
return 44;
}
-(void)tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath
{
if (selectedIndexPath == [self.tableView indexPathForSelectedRow])
{
UIAlertView *a = [[UIAlertView alloc] initWithTitle:#"DeSelect" message:#"DeSelect ??" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"Yes", nil ];
[a show];
}
else
{
UIAlertView *a = [[UIAlertView alloc] initWithTitle:#"Select" message:#"Select ??" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"Yes", nil ];
[a show];
}
}
-(void)alertViewUIAlertView *)alertView clickedButtonAtIndexNSInteger)buttonIndex
{
if (selectedIndexPath == [self.tableView indexPathForSelectedRow])
{
if (buttonIndex==1)
{
selectedIndexPath = [NSIndexPath indexPathForRow:-1 inSection:-1];
// [self tableView:self.tableView heightForRowAtIndexPath:selectedIndexPath];
//[self.tableView reloadData];
//[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:selectedIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//[self.tableView beginUpdates];
//[self.tableView endUpdates];
[self showForIndexPath:selectedIndexPath];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
else
{
if (buttonIndex==1)
{
selectedIndexPath = [self.tableView indexPathForSelectedRow];
//[self tableView:self.tableView heightForRowAtIndexPath:selectedIndexPath];
//[self.tableView reloadData];
//[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:selectedIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// [self.tableView beginUpdates];
// [self.tableView endUpdates];
[self showForIndexPath:selectedIndexPath];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
}
-(void)showForIndexPathNSIndexPath *)indexpath
{
UITableViewCell *c = [self.tableView cellForRowAtIndexPath:indexpath];
CGRect rect = c.frame ;
rect.size.height = 100 ;
c.frame = rect ;
//code to move the cells downward when a cell is selected
for(int i = indexpath.row ; i < [objects count];i++)
{
NSindexpath *row = [NSIndexPath indexPAthforRow:i+1 in Section:0];
UITableViewCell *tmp = [self.tableView cellforindexpath:row];
CGRect frame = tmp.frame;
CGpoint origin = frame.origin;
CGFloat y = origin.y ;
y = y+56; //(100-44)
origin.y = y ;
frame.origin = origin ;
tmp.frame = frame ;
}
NSLog(#"Cell %d :- %# indexpath:- %#",indexpath.row,[c description],indexpath);
}
P.S. -- You can see the attempts I have made to achieve the task by looking at the code that is commented
Keep a flag for yes or no and a index for selected row number.
-(CGFloat)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( flag == 1 && indexpath.row == index )
return 50;
else
return 30;
}
apply your logic of image also similarly when you create cell
please post the code what you have tried.
This link may help you.
Can you animate a height change on a UITableViewCell when selected?.
Use popup button index to change variable value and use that variable in
-(CGFloat)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//change tablecell height based on variable value
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
}
}
Create two tableViewCell for the both casses. Then in your buttonTouch method, remove your previous cell using
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
And then add newCell using:
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

Select Multiple cell in tableView and display the selected cell in another tableView Cell as a label?

Hi I'm creating an app related to iOS default alarm. I'm selecting a multiple cell in tableView. If I click the back button the selected cells are displayed in tableViewCell as a label in another view. I'm Using story board. How to do this?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone) {
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
[myIndexArray addObject:[NSString stringWithFormat:#"%d",indexPath.row]];
}
else
{
thisCell.accessoryType = UITableViewCellAccessoryNone;
for(int i=0; i<myIndexArray.count; i++)
{
if([[myIndexArray objectAtIndex:i]intValue]== indexPath.row)
{
[myIndexArray removeObjectAtIndex:i];
break;
}
}
}
}
The sample image I want like this
I want something like a Repeat View and press back button the selected cells are displayed in Repeat tableViewCell.
I did the same in my app. I can help you...
RepeatDayViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (UITableViewCellAccessoryNone == cell.accessoryType )
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSNumber *dayNumber = [NSNumber numberWithInteger:indexPath.row];
[self.repeatDays addObject:dayNumber];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
NSNumber *dayNumber = [NSNumber numberWithInteger:indexPath.row];
[self.repeatDays removeObject:dayNumber];
}
}
I am passing self.repeatDays to AddAlarmViewController
In
AddAlarmViewController
I have an array like this
_days = [[NSArray alloc ]initWithObjects:#"Sun",#"Mon",#"Tue",#"Wed",#"Thu",#"Fri",#"Sat",nil];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.repeatDays count])
{
NSMutableArray *repeatDays = [NSMutableArray array];
for (NSNumber *dayNumber in self.repeatDays)
{
[repeatDays addObject:[_days objectAtIndex:[dayNumber integerValue]]];
}
NSString *repeatLabel = [repeatDays componentsJoinedByString:#" "];
cell.detailTextLabel.text = repeatLabel;
}
else
{
cell.detailTextLabel.text = NSLocalizedString(#"Never",nil);
}
}
Where ever the user select a row save the action any ware such as NSUserDefaults
in the
-(void)viewDidAppear:(BOOL)animated{
UITableViewCell* testCell = [azanTableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"testCell"]==YES) {
testCell.accessoryType = UITableViewCellAccessoryCheckmark;
testCell .textLabel.textColor = [UIColor colorWithRed:0.22 green:0.33 blue:0.53 alpha:1.0];
}
}
And so on...

UITableView add row below selected row

I had a working tableview where I could double-tap a cell and it would add an 'action' cell below which had four buttons programmed on it.
Today I added alphabetic sections to the tableview and a section index and I can no longer get this functionality to work.
I've added a whole range of NSLogs to the code to try and find the problem and I can't, it seems to be trying to add a row in the same section and one row further down than the cell tapped, so I'm not sure what the problem is. Would anyone have any idea what I'm doing wrong?
If anyone can shed any light on this I would be hugely appreciative. (And apologies if my code is cumbersome or hard to follow, I'm new to this so feel free to suggest what I can improve!)
- (void)viewDidLoad
{
//I start with an array of objects, so I created two arrays; one containing the first letters of each Name, and a list of the number of objects that start with each of those names.
nameIndex = [[NSMutableArray alloc] init];
nameIndexCount = [[NSMutableDictionary alloc]init];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [nameIndex count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.actionRowIndexPath) {
//Returns first letter of the section
NSString *alphabet = [nameIndex objectAtIndex:section];
//Returns the number of entries starting with that letter
NSString *numberofRows = [nameIndexCount objectForKey:alphabet];
int intNumberOfRows = ([numberofRows integerValue] + 1);
return intNumberOfRows;
} else {
NSString *alphabet = [nameIndex objectAtIndex:section];
NSString *numberofRows = [nameIndexCount objectForKey:alphabet];
int intNumberOfRows = [numberofRows integerValue];
return intNumberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"newTableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"newTableViewCell"];
}
//Configure the cell
UIImageView *imageView = [[UIImageView alloc]initWithFrame:cell.frame];
UIImage *image = [UIImage imageNamed:#"LightGrey.png"];
imageView.image = image;
if ([indexPath isEqual:self.actionRowIndexPath]) {
// Four UIButtons coded programmatically
} else {
Contact *p = [[[ContactStore sharedStore]allContacts]objectAtIndex:totalNumberOfRows];
NSString *firstAndLastName = [NSString stringWithFormat:#"%# %#", [p firstName], [p lastName]];
indexPath = [self modelIndexPath:indexPath];
cell.backgroundView = imageView;
// [cell.imageView setImage:smallThumbnailImage];
[cell.imageView setImage:[p thumbnail]];
[[cell textLabel]setBackgroundColor:[UIColor clearColor]];
[[cell textLabel]setText:firstAndLastName];
[[cell detailTextLabel]setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel]setText:[p phoneNumber]];
totalNumberOfRows = totalNumberOfRows + 1;
}
return cell;
}
#pragma mark - Action Row Support
-(NSIndexPath *)modelIndexPath: (NSIndexPath *)indexPath
{
if (self.actionRowIndexPath == nil) {
return indexPath;
}
if ([indexPath row] > [self.actionRowIndexPath row]) {
return [NSIndexPath indexPathForRow:([indexPath row] - 1) inSection:indexPath.section];
}
return indexPath;
}
- (void)handleDoubleTap:(UITapGestureRecognizer *)recognizer {
NSLog(#"Double tap");
CGPoint p = [recognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
NSIndexPath *pathToDelete = self.actionRowIndexPath;
_selectedIndexPath = [self modelIndexPath:_selectedIndexPath];
//Is the user deselecting current row?
if (_actionRowIndexPath) {
[self.tableView deselectRowAtIndexPath:_selectedIndexPath animated:NO];
self.selectedIndexPath = nil;
self.actionRowIndexPath = nil;
} else {
//Selecting a new row
self.selectedIndexPath = indexPath;
self.actionRowIndexPath= [NSIndexPath indexPathForRow:([indexPath row] + 1) inSection:[indexPath section]];
}
[self.tableView beginUpdates];
if (pathToDelete) {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:pathToDelete] withRowAnimation:UITableViewRowAnimationAutomatic];
}
if (self.actionRowIndexPath) {
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:self.actionRowIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
[self.tableView endUpdates];
}
After you get the IndexPath you need to get the IndexPath.row and IndexPath.section and accordingly you need to add the object into your array at the desired index. For example: if you double tap the 2nd row in the 1st section then you need to add the object at index 4 of the array corresponding to the 1st section and then reload table. The cell would be added to the 3rd index of the 1st section.

How do I insert a row at run time into an UITableView on iPhone?

I have created one button with action to add a row to the UITableView at run time but my code is not working. I can see the row animating down, but it's shown animated only on my UITableView row is not added. What can I do in this code to see the row added on cell?
I have 4 sections and I want to add row for 1 section on row 0 and 2 section on row 0:
-(IBAction)add:(id)sender
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray* path = [NSArray arrayWithObject:indexPath];
// fill paths of insertion rows here
[self.mytableview beginUpdates];
[self.mytableview insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];
[self.mytableview deleteRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationBottom];
[self.mytableview endUpdates];
[self.mytableview reloadData];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
NSInteger rows;
if (section==0) {
rows = 4;
//return rowForSectionOne;
//rows=rowForSectionOne++;
}
if (section == 1)
{
rows = 1;
}
return rows;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [mytableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
if ([indexPath row] == 0 && [indexPath section] == 0)
{
cell.textLabel.text=#"Title";
cell.accessoryView = textField;
titlename=textField.text;
[[cell imageView] setImage:[UIImage imageNamed:#"DetailViewDue.png"]];
NSLog(#"******:%#",titlename);
}
if ([indexPath row] == 1 && [indexPath section] == 0)
{
cell.textLabel.text=#"Tags";
cell.detailTextLabel.text=app.Tags;
[[cell imageView] setImage:[UIImage imageNamed:#"DetailViewTag.png"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if ([indexPath row] == 2 && [indexPath section] == 0)
{
cell.textLabel.text=#"Notes";
cell.detailTextLabel.text=app.Notes;
[[cell imageView] setImage:[UIImage imageNamed:#"DetailViewNote.png"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
fromDate = [[dateFormat stringFromDate:selectionData.fromDateSelected]retain];
if ([indexPath row] == 3 && [indexPath section] == 0)
{
cell.textLabel.text=#"DueDate";
cell.detailTextLabel.text=fromDate;
[[cell imageView] setImage:[UIImage imageNamed:#"DetailViewDue.png"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if ([indexPath row] == 0 && [indexPath section] == 1)
{
cell.textLabel.text=#"Attach";
}
return cell;
}
Well you are doing it right. Lets say when the button is pressed -(IBAction)add:(id)sender is invoked. then compose indexPath with the proper row & section. Here section is 0,1,2,3 (since you have 4 sections -
NSIndexPath *indexPath0 = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:1];
NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:0 inSection:2];
NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:0 inSection:3];
//put these indexpaths in a NSArray
[tableView insertRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
This should update the table. No need to do reloadData on the table as you are only adding one row (& not changing the entire table). Also make sure the dataSource has this new added entry per section otherwise your app will crash
You only have to add few lines of code in "cellForRowAtIndexPath" method
if(cell ==nil)
{
cell =[[UITableViewAlloc alloc]initWithStyle.... ]
}
int theRow = indexPath.row;
if(indexPath.section == 1) theRow += 3;
if(indexPath.section == 2) theRow += 5;
if(indexPath.section == 3) theRow += 4;
if(indexPath.section == 4) theRow += 3;
//load the view in it
cell.textLable . text = [<your object> objectAtIndexPath.row];
return cell;
Here you can add rows as many as you want....

tableView:cellForRowAtIndexPath: not getting called when using searchbar

I have a viewcontroller with a nib - which has a tableview, searchbar and searchdisplaycontroller inside.
The searchdisplaycontroller's contentscontroller, results delegate, delegate and results datasource is wired to the viewcontroller in IB. The searchbar's delegate is wired to the view controller in IB. The main tableview is also wired to the viewcontroller and its loading items during runtime properly.
Everything seems to work except the resultstableview - it never gets populated and the tableView:cellForRowAtIndexPath: never gets called AFTER the user types into the searchbar - it only gets called to populate the main tableview.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
// Dequeue or create a cell o f the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (tableView.tag == 2)
{
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
// Configure the cell.
NSHotel *selectedHotel = [[self hotelList] objectAtIndex:[indexPath row]];
//Store the hotel id for use later
selectedHotel.id = [indexPath row];
//cell.textLabel.text = [NSString stringWithFormat:#"Catalonia Majorica", indexPath.row];
cell.textLabel.text = [selectedHotel name];
}
else if (tableView.tag == 1)
{
cell.accessoryType = UITableViewCellAccessoryNone;
// Configure the cell...
NSAirport *selectedAirport = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
selectedAirport = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
selectedAirport = [self.listContent objectAtIndex:indexPath.row];
}
//Set the label of the cell formatting the distance from the device
cell.textLabel.text = [NSString stringWithFormat:#"%# - %# miles",
selectedAirport.name, [self formattedStringWithDecimal:selectedAirport.milesFromDevice]];
//Adjust the front of the label
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
}
return cell;
}
Fixed it - it was returning 0 here:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.filteredListContent count];
}
else if (tableView.tag == 1)
{
return [self.listContent count];
}
else if (tableView.tag == 2)
{
// Return the number of rows in the section.
return [[self hotelList] count];
}
NSLog(#"The rows in tableview!");
return 0;
}