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

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.
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
                        You can try.
[messages insertObject:messageField.text atIndex:0];
instead of [messages addObject:messageField.text];.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With