【问题标题】:Array & TableView : only add new itemsArray & TableView : 只添加新项目
【发布时间】:2018-02-09 17:42:44
【问题描述】:

我有一个数据库,想制作一个显示消息的应用程序。

在我的 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"]
}

然后我不想重新加载所有表格:我只想在 1 之间的表格中添加 ["uid": 10, "msg": "NEW"] 新消息. 和 2. 用户的消息,带有轻柔的动画推送两条已经存在的消息。

有可能吗?

问题是我无法弄清楚,我如何检查 新获取的数据 的数组中哪些项目是新的,而不是旧的 globalMessages ,如果有的话就用动画显示出来。

如果某些项目不再在新获取的数据 中,则使用表格视图中的动画将其删除。 ??

目前我正在这样做:

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)
        })
}

【问题讨论】:

    标签: ios arrays swift uitableview


    【解决方案1】:

    您可以将字典用作各种查找表:

    // 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 数组将包含您的新消息。

    【讨论】:

      【解决方案2】:

      你可以这样插入

       tableView.beginUpdates()
       tableView.insertRows(at: [IndexPath(row:1, section: 0)], with: .automatic)
       tableView.endUpdates()
      

      但首先将新数据追加到数组中正确的位置

      globalMessages.insert(["uid": 10, "msg": "NEW"], at: 1)
      

      【讨论】:

        【解决方案3】:

        假设您有两个数组,newArrayoldArray。您迭代newArray 并检查oldArray 中是否存在项目,如果不存在,则将索引设为indexPaths,并将它们放入名为insertIndexPaths 的数组中。做同样的事情来迭代oldArray 并找出不存在的项目并将它们放入removeIndexPaths。最后,您从tableView 拨打insertRowsAtIndexPathsdeleteRowsAtIndexPaths

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-23
          • 1970-01-01
          • 2013-11-10
          • 1970-01-01
          • 1970-01-01
          • 2021-01-15
          • 1970-01-01
          • 2016-04-30
          相关资源
          最近更新 更多