Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cell/data to the top of UITableView

I'm trying to create a simple chat application for iOS. It currently looks like this:

enter image description here

I want to change the order that the messages is displayed, i.e. display the latest message over the older messages. My current implementation looks like this:

// Datasource for the tableView
messages  = [[NSMutableArray alloc] init];

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

    [...]
    // messageTextView is a contentView subView.
    messageTextView.text = [messages objectAtIndex:indexPath.row];
    [...]

- (IBAction)sendMessage:(id)sender
{
    [messages addObject:messageField.text];
    messageField.text = @"";
    [self.tableView reloadData];

    /*
     I have tried the implementation below, but I always got an exception.
     [self.tableView beginUpdates];
     NSIndexPath *path1 = [NSIndexPath indexPathForRow:1 inSection:0]; 
     NSArray * indexArray = [NSArray arrayWithObjects:path1,nil]; 
     [self.tableView insertRowsAtIndexPaths:indexArray 
     withRowAnimation:UITableViewRowAnimationTop];
     [self.tableView endUpdates];
     */

}

Any tips on how to do this would be great.

Thanks.

like image 207
Anders Avatar asked Dec 04 '22 06:12

Anders


2 Answers

Simple you need to insert the new UITableViewCell at the 0 index. Also modify your Datasource otherwise your app will crash. Below I show how to modify your UITableView. Modifying your datasource is easy.

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];

What you are essentially doing here is inserting the new chat message cell at the 0th index position. You could use a nice animation effect to make it appear or fade in.

There are various animations that you can use here-

UITableViewRowAnimationBottom
UITableViewRowAnimationFade
UITableViewRowAnimationMiddle
UITableViewRowAnimationNone
UITableViewRowAnimationRight
UITableViewRowAnimationTop
like image 122
Srikar Appalaraju Avatar answered Dec 15 '22 03:12

Srikar Appalaraju


You can try.

[messages insertObject:messageField.text atIndex:0];

instead of [messages addObject:messageField.text];.

like image 41
Himanshu A Jadav Avatar answered Dec 15 '22 02:12

Himanshu A Jadav