Ios – How to we dynamically add new cell between two given cell in TableView

iosipaduitableviewxcode

I need to add a new cell on selection of a cell of table. The new cell should come below the selected cell. Can we do it?

Below is the code where I am creating 4 cells and want to insert a cell between 2 and 3.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];


if(indexPath.row == 0){

    cell.textLabel.text = @"My Tweets";
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor blackColor];
    cell.imageView.image = [UIImage imageNamed:@"tweets.png"];
}

if(indexPath.row == 1){

    cell.textLabel.text = @"Search";
    cell.backgroundColor = [UIColor blackColor];

    cell.textLabel.textColor = [UIColor whiteColor];
    cell.imageView.image = [UIImage imageNamed:@"search.png"];
}

if(indexPath.row == 2){

    cell.textLabel.text = @"Followers";
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor blackColor];
    cell.imageView.image = [UIImage imageNamed:@"followers.png"];
}

if(indexPath.row == 3){

    cell.textLabel.text = @"Following";
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor blackColor];
    cell.imageView.image = [UIImage imageNamed:@"following.png"];
}



return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

//here I have to insert a new cell below on the click this existing cell.


if(indexPath.row == 1)
{

    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
    NSArray *indexPaths = [NSArray arrayWithObject:newIndexPath]; 

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPaths] withRowAnimation:UITableViewRowAnimationAutomatic];
}

}

Best Answer

You should update your data source and then call this UITableView method:

- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

This is going to call the

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

method of the table view data source, and update your table, with the animation that you choose.

You would not create the new cell in the didSelectRowAtIndexPath method as you are doing in the code that you posted.


edited to add info.

To set the indexPaths array (for your case) you can do this:

NSInteger row = [indexPath row];
NSInteger section = [indexPath section];    
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row+1 inSection:section];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath]; 
Related Topic