Add a row dynamically in TableView of iphone - iphone

I need to add a new row in the tableview when i select a row in the table.
Am i suppose to use the following method???
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation
What shoud i write inside the method to add a new row.?
Please do help me,
Thanks in advance
Shibin.

When I add a row dynamically, I use insertRowsAtIndexPaths: here is an example function
- (void) allServersFound {
// called from delegate when bonjourservices has listings of machines:
bonjourMachines = [bonjourService foundServers]; // NSArray of machine names;
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
int i = 0;
for (NSArray *count in bonjourMachines) {
[tempArray addObject:[NSIndexPath indexPathForRow:i++ inSection:0]];
}
[[self tableView] beginUpdates];
[[self tableView] insertRowsAtIndexPaths:(NSArray *)tempArray withRowAnimation:UITableViewRowAnimationNone];
[[self tableView] endUpdates];
[tempArray release];
}

If you are filling your table from an array, you can just add an element to your array and call [myTable reloadData]

reload data is nice and simple, but does not animate as far as I can tell...

ReloadData can add row in teble view but if you want some animation when row add then you should use these lines of code.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]];
[mainArray insertObject:#"new row" atIndex:indexPath.row+1];
[[self tableView] beginUpdates];
[[self tableView] insertRowsAtIndexPaths:(NSArray *)tempArray withRowAnimation:UITableViewRowAnimationFade];
[[self tableView] endUpdates];
}

Related

what should I do if I want to see the tablview from the last [duplicate]

This question already has answers here:
How to Start UITableView on the Last Cell?
(8 answers)
Closed 9 years ago.
hey I want to make a demo of chat.so when I open UITableView for it, it should display from the last and previous item should be in upper side.. i.e., I want to scroll my UITableView to the last row automatically when user opens the chat screen. what should i do?
my code is-
cell = [tv dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
}
[lblName setFont:[UIFont fontWithName:#"Arial" size:12]];
lblName.lineBreakMode = NSLineBreakByWordWrapping;
lblName.numberOfLines = 0;
lblName.text=[arrUsername objectAtIndex:indexPath.row];
lblName.textColor = [UIColor blackColor];
[lblName setBackgroundColor:[UIColor grayColor]];
if ([[arrCommentUid objectAtIndex:indexPath.row] isEqualToString:#"1"]) {
[lblName setTextAlignment:NSTextAlignmentLeft];
}
else
please help!! its the code for just optional.cell of UITableView
try this for chat application
SSMessagesviewcontroller
stbubbletableviewcell
bubblethingie
uibubbletableview
styledchat
acanichat
and also you can go to last row using
[tableView reloadData];
int lastRowNumber = [tableView numberOfRowsInSection:0] - 1;
NSIndexPath* ip = [NSIndexPath indexPathForRow:lastRowNumber inSection:0];
[tableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:NO];
In order to do this, you should sort your array in descending order.Thus it will display your data from last to first.
For that you can use NSSortDescriptor
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
NSArray* sortedArray = [<YOURS_ARRAY> sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Enjoy Programming !
You can scroll to last using scrollToRowAtIndexPath
[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
And you can get indexPath of last row using
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:([yourTableAry count] - 1) inSection:0];
Or
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:([tableView numberOfRowsInSection:0] - 1) inSection:0];
EDIT
If you want to goto top of row then
NSIndexPath *firstRowIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView scrollToRowAtIndexPath:firstRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

How to insert row to n number of sections dynamically in UITableview

How to update number of rows in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
}
When it will expand increase number of rows.
`- (void) rotateButtonToExpanded:(UIButton*)aButton section:(int)aSection{
// Rotate the button with animation.
[UIView beginAnimations:ROTATE_TO_EXPAND context:nil];
[UIView setAnimationDuration:ANIMATION_DURATION];
aButton.transform = CGAffineTransformMakeRotation(M_PI*2.5);
[UIView commitAnimations];
// Save the state (expanded or collapsed) of button with index path as key.
BOOL isExpanded=![[mStateOfNodes objectAtIndex:aSection] isExpanded];
[[mStateOfNodes objectAtIndex:aSection] setIsExpanded:isExpanded];
NSArray*theDataOfChildCells=[[self.mNodes objectAtIndex:aSection] valueForKey:CHILD_NODES];
for (int i=0; i<theDataOfChildCells.count; i++) {
mNumberOfCells++;
[self beginUpdates];
NSIndexPath*theIndexPath=[NSIndexPath indexPathForRow:i inSection:aSection];
[self insertRowsAtIndexPaths:[NSArray arrayWithObject:theIndexPath] withRowAnimation:UITableViewRowAnimationMiddle];
[self endUpdates];
}
}`
used reload data methods,
[self.tableview reloadData];
Use Following code that use for add row in UITable with specific row and section
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowNO inSection:SectionNO];
[self.tblView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
rowNO=rowNO+1;
[self.tblView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
[self.tblView reloadData];

How to tell if cell was inserted or reloaded in cellForRowAtIndexPath?

I need to set different styles for cells that I have inserted compared to reloaded ones.
I am inserting my cells like the following:
[tempArray addObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[[self tableView] beginUpdates];
[[self tableView] insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
[[self tableView] insertRowsAtIndexPaths:(NSArray *)tempArray withRowAnimation:UITableViewRowAnimationNone];
[[self tableView] endUpdates];
Is there a way for me to do the following:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (cell was inserted) {
cell.mylabel.textColor = [UIColor redColor];
} else {
cell.mylabel.textColor = [UIColor blackColor];
}
}
As is often the case for maintaining the state of a table view cell, the right answer is to keep the state in your model. In other words, if tempArray is your model containing a collection of objects that describe the table's contents, add a BOOL attribute to those objects meaning something like userAdded.
Then your "cell was inserted" pseudo-code can become:
MyModelClass *modelElement = [tempArray objectAtIndex:indexPath.row];
if (modelElement.userAdded) {
cell.mylabel.textColor = [UIColor redColor];
} else {
cell.mylabel.textColor = [UIColor blackColor];
}

Hiding the table view cells with switch ON/OFF in iPhone

This may be a simple question for you experts but I can't figure out the correct solution.
In my app I created a a table view to list a no of items.
In the first row of the cell there a switch (ON/OFF).
So my client need to hide the bottom cells(other than zeroth cell) when switch is OFF and show all the cells when switch is ON.
I created the switch through code.
Can anyone please help me with how to do this?
Thanks in advance.
numberOfRows dataSource method - make it return 1 and reloadTableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/// ....
self.switchView = [[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
cell.accessoryView = self.switchView;
[self.switchView setOn:NO animated:NO];
[self.switchView addTarget:self action:#selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
//....
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if [self.switchView.on]
return 1;
else
{
// normal code return
}
}
- (void) switchChanged:(id)sender {
[self.tableView reloadData];
}
You could use insertRowsAtIndexPaths, this will not only add, but also do the animation of adding new row
first add target UIControlEventTouchUpInside into UISwitch.
[switch addTarget:self action:#selector(switchChange:) forControlEvents:UIControlEventValueChanged];
-(void) switchChange:(UISwitch*) sender{
isSwitchOn = sender.on; //edited
[myTable beginUpdates];
NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0];
NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0];
//you may add as many row as you want here.
[myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationMiddle];
[myTable endUpdates];
}
and make sure you will add how many rows you will insert in numberOfRowsInSection:
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isSwitchOn) return 1;
else
return 3; //how many rows would have after switched on
}
You might want to check [myTable insertSections:withRowAnimation: to insert another section and do the same as above. but remember to state how many section you will add, in numberOfSectionsInTableView:
UPDATE :
implement deleteRowsAtIndexPaths: if switch off.
-(void) switchChange:(UISwitch*) sender{
isSwitchOn = sender.on;
if(isSwitchOn){
[myTable beginUpdates];
NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0];
NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0];
//you may add as many row as you want here.
[myTable insertRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationMiddle];
[myTable endUpdates];
}
else{
[myTable beginUpdates];
NSIndexPath *row1 = [NSIndexPath indexPathForRow:1 inSection:0];
NSIndexPath *row2 = [NSIndexPath indexPathForRow:2 inSection:0];
//you may add as many row as you want here.
[myTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects:row1,row2,nil] withRowAnimation:UITableViewRowAnimationFade];
[myTable endUpdates];
}
}
There's a UITableViewDataSource method called tableView:numberOfRows:inSections method.Just check for the state of the switch and return 1 if it's OFF or all the rows if it is ON. Just call the [tableView reloadData] method each time you switch ON and OFF. As simple as that.

tablerow delete but still showon in table view

my data is show on the table whn i select data to delet its delted from database but not from table , i go back to other view and again come to the delete table view then delete data is not show again
i am using this code ...
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPath withRowAnimation:(UITableViewRowAnimation)animation
{
NSLog(#"Hello");
}
-(void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// int row = [indexPath row];
[self.table beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
Hadits *delHadit = [self.allBookMarks objectAtIndex:indexPath.row];
dbAccess *dbmethods = [[dbAccess alloc] init];
NSInteger delHaditid = delHadit.haditid;
[dbmethods deleteBookMark:delHaditid];
[dbmethods release];
}
[self deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.table endUpdates];
NSLog(#"Hello");
[self.table reloadData];
}
...Help needed..
Regards Haseeb
in view will appear prepare your array which having record and in commitEditing add one line.
[self viewWillApear:YES];
and in viewWillAppear add this line
[yourTable reloadData];
after fetching data from db.
There is little mistake (or I think the relevant code is not shown). You have deleted the entry from the database, but I think you have missed to delete the same from your array which acts as your tableview datasource.
-(void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.table beginUpdates];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject: indexPath] withRowAnimation:UITableViewRowAnimationFade];
Hadits *delHadit = [self.allBookMarks objectAtIndex:indexPath.row];
dbAccess *dbmethods = [[dbAccess alloc] init];
NSInteger delHaditid = delHadit.haditid;
[dbmethods deleteBookMark:delHaditid];
[dbmethods release];
[self.allBookMarks removeObject:delHadit];/// change of code
}
//[self.table reloadData];
[table endUpdates];
}