Anders Anders - 4 months ago 24
Objective-C Question

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
[self.tableView endUpdates];


Any tips on how to do this would be great.



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-