[英]Add cell/data to the top of UITableView
我正在尝试为iOS创建一个简单的聊天应用程序。 它目前看起来像这样:
我想更改消息显示的顺序,即显示旧消息的最新消息。 我目前的实现如下:
// 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];
*/
}
任何有关如何做到这一点的提示都会很棒。
谢谢。
很简单,您需要在0索引处插入新的UITableViewCell
。 同时修改您的数据源,否则您的应用程序将崩溃。 下面我将展示如何修改UITableView
。 修改数据源很容易。
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];
你在这里做的是在第0个索引位置插入新的聊天消息单元格。 您可以使用漂亮的动画效果使其显示或淡入。
你可以在这里使用各种动画 -
UITableViewRowAnimationBottom
UITableViewRowAnimationFade
UITableViewRowAnimationMiddle
UITableViewRowAnimationNone
UITableViewRowAnimationRight
UITableViewRowAnimationTop
你可以试试。
[messages insertObject:messageField.text atIndex:0];
而不是[messages addObject:messageField.text];
。
快速解决方案
像这样定义数组
var arrMessage = [AnyObject]()
和按钮操作
@IBAction func btnSendMessageTapped(sender: AnyObject) {
arrMessage.insert(txtTypeMessage.text!, atIndex: 0)
txtTypeMessage.text = ""
self.tblMessage.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.