将 JSON 响应附加到表视图 -Swift

Append JSON response to tableview -Swift

我正在调用 returns 用户信用卡的 json 响应的 PFCloud 函数,我想显示一些卡数据。我有一个我试图追加的数组,但它无法显示。我在 viewDidLoad 中调用了这个函数。

func loadCards(){

    if let customer = PFUser.currentUser()?.objectForKey("stripe_customer_id") as? String {

        PFCloud.callFunctionInBackground("listCards", withParameters: ["customerId": customer], block: { (success: AnyObject?, error: NSError?) -> Void in

            if error != nil {
                println(error)
            }
            else {
                let responseString = success as? NSArray

                    if let cardToDisplay = responseString!.valueForKey("cardId") as? NSArray{


                        println(cardToDisplay)
                        self.displayCards.addObject(cardToDisplay)


                    }

                self.tableView.reloadData()
            }

        })
    }

}



// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    println(self.displayCards.count)
    return self.displayCards.count

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

 self.displayCards[indexPath.row] = cell.card.text!
return cell
}

这是我在控制台的日志:

0
0
0
0
0
0
(
"card_16v8teBnRIkk4qBepmuz2Mlk",
"card_16ymjoBnRIkk4qBeirtCdYdn",
"card_16ymfzBnRIkk4qBebvP4wwNO",
"card_16ymfzBnRIkk4qBeoRUVccws",
"card_16ymaPBnRIkk4qBeK2ju6ckP",
"card_16ylqyBnRIkk4qBeffUN2bwo",
"card_16ylq3BnRIkk4qBePGngNz8H"
)
1
  • 您需要在主线程中重新加载 tableView。当你进入后台发出请求时,你需要做:

    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        self.tableView.reloadData()
    }
    

    而不只是 self.tableView.reloadData()

  • cardToDisplay好像是数组,所以把self.displayCards.addObject(cardToDisplay)改成self.displayCards = cardToDisplay

  • cellForRowAtIndexPath 中的行 self.displayCards[indexPath.row] = cell.card.text! 应该是相反的。您应该将文本设置为 self.displayCards[indexPath.row]。所以应该是cell.card.text = self.displayCards[indexPath.row]