表视图和外部数据源

tableview and external data sources

我有一个带有 UITable 视图的视图控制器。

我的数据源是外部的。我已经使用数据任务转到某些带有某些参数的 URL,取回 JSON 响应,最后我得到一个包含我希望添加的数据的 Swift 字典对象到 table 视图单元格。这一切都发生在 viewdidload 函数中。

我将如何去用我的字典中的数据填充我的 table 因为这需要在我收到我的数据后发生?

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
    cell.myLabel.text = json_surveys[indexPath.row]["SName"]
    return (cell)

}

那么我如何告诉 table查看我的字典,但只有在我真正拥有字典之后?

每当您从服务器收到数据时使用self.tableView.reloadData()。这将重新加载 tableView.

的所有单元格

听起来您想从完成数据任务的内部重新加载数据,您会想像这样将调用分派到主线程

DispatchQueue.main.async {
    self.tableView.reloadData()
}

您需要将 tableView 委托和数据源分配给此 UIViewController

你可以这样做:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
....

那么你需要在这个class.

中添加cellForRownumberOfRows协议函数

我看到您已经在添加 cellForRow,您还应该添加 numberOfRows 函数,这就是您收到错误的原因。

这样添加:

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

然后您可以在完成从服务器获取数据并将其添加到数组中时调用 tableView.reloadData(),例如数据数组。