0

我有关于 tableView 的问题。我正在聊天模块上快速开发一个项目。我正在从 Web 服务获取数据。第一次加载视图时,我的聊天单元格看起来很完美。但是当我发送消息或滚动 tableView 时,值会更改或丢失。任何人都可以帮我解决这个问题。我在这个问题上停留了很长时间。

4

2 回答 2

1

我有关于 tableView 的答案。scnr _

您需要跟踪 tableViewdataSource以及 tableView 本身中数据的更改。

编辑:假设您的聊天数据是一个字符串数组,按日期排序,最新消息在顶部,在插入数据时,您应该

tableView?.beginUpdates() // signal the tableview a pending update
data.insert(newMessage, atIndex:0) // modify your dataSource's data
tableView?.insertRowsAtIndexPaths([NSIndexPath(0, inSection: 0)], withRowAnimation: .Automatic) // insert the new row in the tableView
tableView?.endUpdates() // commit changes
于 2016-01-20T12:40:32.323 回答
0

您的数据源应与 tableView 索引协调。即应该有一个规则来确定应该显示的消息和 tableView 的 IndexPath。最简单的规则如下,假设您的 tableView 仅包含 1 个部分,您的 dataSource 中的 indexOf 消息应该等于 IndexPath.Row。例如,您正在发送一条新消息,该消息应添加到 tableView 的底部

dataSource.append(newMessage)
tableView.insertRowsAtIndexPaths([NSIndexPath(0, inSection: 0)], withRowAnimation: .Automatic)

并在您的 cellForRowAtIndexPath 委托方法中

let message = dataSource[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("MessageCell", forIndexPath: indexPath)
// then use the message to populate the cell then return cell

return cell
于 2016-01-20T13:24:25.597 回答