Adding a cell / data to the top of a UITableView

I am trying to create a simple chat application for iOS. Currently, it looks like this:

enter image description here

I want to change the display order of messages, i.e. display the last message on top of old messages. My current implementation is as follows:

// 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 advice on how to do this would be great.

Thanks.

+4
source share
3 answers

You just need to insert a new UITableViewCell into index 0. Also change your data source, otherwise your application will crash. Below I will show how to change your UITableView . Modifying the data source is simple.

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [tableView beginUpdates]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; [tableView endUpdates]; 

What you basically do here is insert a new chat message cell at the 0th position of the index. You can use a nice animation effect to make it appear or disappear.

There are various animations you can use here -

 UITableViewRowAnimationBottom UITableViewRowAnimationFade UITableViewRowAnimationMiddle UITableViewRowAnimationNone UITableViewRowAnimationRight UITableViewRowAnimationTop 
+11
source

You can try.

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

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

+6
source

Fast decision

Define an array like this

  var arrMessage = [AnyObject]() 

and button action

  @IBAction func btnSendMessageTapped(sender: AnyObject) { arrMessage.insert(txtTypeMessage.text!, atIndex: 0) txtTypeMessage.text = "" self.tblMessage.reloadData() } 
0
source

Source: https://habr.com/ru/post/1379642/


All Articles