【问题标题】:Repeating values on a table view cells Error from API response在表格视图单元格上重复值来自 API 响应的错误
【发布时间】:2015-08-20 07:28:55
【问题描述】:

我有一个带有按钮的视图(我们称之为视图 1)。单击按钮时,我向我的 API 发出 GET http 请求。它发回一组对象。

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

我将返回的 JSON 响应从视图 1 传递到视图 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 响应。

在视图 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
  }

问题:

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

我的问题:

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

【问题讨论】:

    标签: ios json swift uitableview


    【解决方案1】:

    您不需要使用for 循环(因此,我猜表格视图会不断重复值)。 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.
    }
    

    希望这会有所帮助!

    【讨论】:

    • 非常感谢。这真的很有帮助!您如何显示单击新视图的表格视图单元格的详细信息。基本上就像每个表格视图单元格的详细视图?
    • 您可以使用 segue 将您的单元格与详细视图绑定。请接受我的回答
    • 那么将单元格绑定到详细视图并通过segue 传递数据?您能否提供任何指向现有示例的链接
    • 是的,然后您可以使用prepareForSegue 传递数据。暂时没有链接。你应该谷歌它
    猜你喜欢
    • 2012-08-27
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多