我有一个数据库,想制作一个显示消息的应用程序。
在我的 swift 应用程序中有一个变量,让我们用一些随机值填充它
var globalMessages:
{
["uid": 1, "msg": "test1"],
["uid": 2, "msg": "test2"],
["uid": 3, "msg": "test3"],
}
我使用 urlSession 从网络获取这些数据:
{
["uid": 1, "msg": "test1"],
["uid": 10, "msg": "NEW"], //new data
["uid": 2, "msg": "test2"],
["uid": 3, "msg": "test3"]
}
然后我不想重新加载所有表格:我只想将 ["uid": 10, "msg": "NEW"] 新消息添加到 1 之间的表格中. 和 2. 用户的消息,用柔和的动画推送两条已经存在的消息。
有可能吗?
问题是我无法弄清楚,如何检查新获取的数据数组中的哪些项目是新的,而不是旧的globalMessages中的项目,如果有则用动画显示。
如果某些项目不再位于新获取的数据中,则使用动画将其从表格 View 中删除。 ??
目前我正在这样做:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return globalMessages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BubbleCell", for: indexPath) as! BubbleCell
let bubble = globalMessages[indexPath.row]
cell.messageLabel.text = bubble.message
let typeColor = UIColor(rgb: 0xE2E2E2)
if let image = UIImage(named: "bubble") {
let h = image.size.height / 2
let w = image.size.width / 2
cell.bubbleImageView.image = image
.resizableImage(withCapInsets:
UIEdgeInsetsMake(h, w, h, w),
resizingMode: .stretch).withRenderingMode(.alwaysTemplate)
cell.bubbleImageView.tintColor = typeColor.withAlphaComponent(0.85)
}
return cell
}
并且应用程序每 10 秒使用一个全局计时器将数据从网络下载到 globalMessages 数组中,然后通过通知推送重新加载表格:
@objc func notification_reloadTableView(){
DispatchQueue.main.async(execute: {() -> Void in
let range = NSMakeRange(0, self.tableView.numberOfSections)
let sections = NSIndexSet(indexesIn: range)
self.tableView.reloadSections(sections as IndexSet, with: UITableViewRowAnimation.fade)
})
}
最佳答案
您可以使用字典作为某种查找表:
// For simplicity, I'm pretending you have a "Message" object that
// would be in each element of that array you are using.
// This would be a private class level variable.
var messageLookup: [String : Message] = [:]
// And then later, probably in a method you can do the following:
var newMessages: [Message] = []
var updatedMessageLookup: [String : Message] = [:]
// You just got your new batch of messages, I'll say they're in
// an array called "messages".
for message in messages
{
if messageLookup[message.UID] == nil
{
// It's not in your lookup, so it is new.
newMessages.append(message)
}
// As we enumerate, build up what will become the new lookup.
updatedMessageLookup[message.UID] = message
}
messageLookup = updatedMessageLookup
最后,newMessages 数组将包含您的新消息。
关于ios - 数组和表格 View : only add new items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48711357/