ios - 在表格 View 单元格上重复值 来自 API 响应的错误

标签 ios json swift uitableview

我有一个 View (我们称之为 View 1),上面有一个按钮。单击按钮后,我向我的 API 发出 GET http 请求。它发回一组对象。

目前我正在尝试做的是,当用户按下 view 1 上的按钮时,响应数据将传递给 view 2,这是一个 < em>tableView。然后用返回的数据填充表格 View 单元格。

我将返回的 JSON 响应从 View 1 传递到 View 2,如下所示:

    dispatch_async(dispatch_get_main_queue()) {

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    let vc = storyboard.instantiateViewControllerWithIdentifier("BioView") as! BioTableViewController

                    vc.bioArray = parseJSON
                    self.presentViewController(vc, animated: true, completion: nil)

                }

其中 parseJSON 包含返回的 JSON 响应。

在 View 2 中,我有以下内容:

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
       {

            return self.bioArray.count

       }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("bioCell", forIndexPath: indexPath) as! UITableViewCell

    // Configure the cell...

    if bioArray.count > 0 {

        let weatherSummary: AnyObject = bioArray[indexPath.row]
        for x in bioArray {
            if let id = x["employeeName"] as? String{
                cell.textLabel?.text = id
            }
          }
        }

    return cell
  }

问题:

TableView 不断重复返回的 JSON 数据中的最后一个值。见下文:

enter image description here

我的问题:

如何阻止值重复并显示响应数据中的所有值,当我点击一个表格 View 单元格时,它会转到另一个 View 并显示与点击的单元格相关的所有详细信息。

最佳答案

你不需要使用 for 循环(因为它, TableView 保持重复值我猜)。 cellForRowAtIndexPath 将为您做同样的事情。试试下面的代码:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("bioCell", forIndexPath: indexPath) as! UITableViewCell

    // Configure the cell...

        let weatherSummary: AnyObject = bioArray[indexPath.row]

            if let id = weatherSummary["employeeName"] as? String //Dont know the exact syntax.
            {
                cell.textLabel?.text = id
            }

    return cell
  }

要摆脱 if bioArray.count > 0 条件,您可以这样做

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{
   return self.bioArray.count ?? 0 //This will return 0 rows if bioArray is empty.
}

希望这会有所帮助!

关于ios - 在表格 View 单元格上重复值 来自 API 响应的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32112049/

相关文章:

ios - 通过代码实现 Segue

ios - SwiftUI - 从 NSObject 继承的 ObservableObject 在 iOS 13 中不会更新

ios - 如果对象无论如何都将被销毁,为什么我们在 dealloc 时将委托(delegate)设置为 nil?

javascript - 如何在 jQuery ajax 调用中将 JSON 响应解析为 JSONP?

ios - 更改付款上下文选择的付款方式

ios - 在 Coordinator 模式中重用 View Controller

json - 当输入JSON具有 “_source”字段时,ES没有结果

javascript - 从数据库中解析JSON并显示在前端

ios - header 未显示在 UICollectionViewController Swift 中

swift - 在 Swift 5 中的泛型方法中展开可选类型