【问题标题】:UITableview appends new cells below old when I call reloadData()当我调用 reloadData() 时,UITableview 会在旧单元格下方附加新单元格
【发布时间】:2018-05-12 12:17:14
【问题描述】:

问题:

当我从数据源重新加载数据时,我希望我的 tableView 清除旧单元格。当我在展开 segue 上加载表时,数据源从 json blob 获取所有新数据,但是当我调用 reloadData() 即使我的数据源数组包含时,表中的旧单元格仍然存在只有新数据。

代码:

主视图控制器:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var sourceArray=[String]()
    var otherClassVariable: Any?

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sourceArray.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        cell.textLabel?.text = sourceArray[indexPath.row]
        return cell
    }

    func getNewDataAndUpdateTable() {
        //Remove all from sourceArray
        self.sourceArray.removeAll()
        let param = self.otherClassVariable
        let url = URL(string: "https://myurl.com/"+param)!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

            if error != nil {
                print(error as! String)
            } else {
                if let urlContent = data {
                    do {
                        let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, Any>>

                        //Repopulate source Array
                        for thing in jsonResponse {
                            self.sourceArray.append(thing)
                        }

                        Dispatch.main.async {
                            //Reload data in main thread
                            self.tableView.reloadData()
                        }
                    } catch {
                        print("json failed")
                    }
                }
            }
        }

        task.resume()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getNewDataAndUpdateTable()

    }

    @IBAction func unwindToViewController(_ sender: UIStoryboardSegue) {
        if sender.source is SecondViewController {
            if let senderVC = sender.source as? SecondViewController{
                self.otherClassVariable = senderVC.updatedOtherClassVariable as String!
                getNewDataAndUpdateTable()
            }
        }
    }
}

【问题讨论】:

  • 那是因为您在向其中添加新记录之前没有清除数据源数组。
  • @BenJ 你能分享所有相关代码吗?我的意思是与 getNewDataAndUpdateTable() 函数相关的完整代码?

标签: ios swift uitableview


【解决方案1】:

之所以如此,是因为您将新数据附加到您的 sourceArray,但您应该分配它。

更新代码:

func getNewDataAndUpdateTable() {
    //Remove all from sourceArray
    self.sourceArray.removeAll()
    let param = self.otherClassVariable
    let url = URL(string: "https://myurl.com/"+param)!

    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

        if error != nil {
            print(error as! String)
        } else {
            if let urlContent = data {
                do {
                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, Any>>

                    //Repopulate source Array
                    self.sourceArray = jsonResponse // Assign response to the source array

                    Dispatch.main.async {
                        //Reload data in main thread
                        self.tableView.reloadData()
                    }
                } catch {
                    print("json failed")
                }
            }
        }
    }

    task.resume()

}

【讨论】:

  • 谢谢。这对我有用。追问:为什么 self.sourceArray.removeAll() 没有在 getNewDataAndUpdateTable() 开头完成这个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多