我试图显示一个包含两条信息的表格 View :一个地方的名称(在称为“候选人”的代码中)和它收到的投票数。我从两个不同的类获取这两条信息,存储在 Parse 上。
我可以很好地获取该地点的名称 - 它是存储在我在 queryForTable() 函数中查询的主表中的数据,并使用 tableView(tableView: cellForRowAtIndexPath indexPath: object:) 函数显示:
import UIKit
import Parse
import ParseUI
class CategoryViewController: PFQueryTableViewController {
var currentObject : PFObject?
var candidates: Array<AnyObject>?
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.parseClassName = "CategoryCandidates"
self.textKey = "candidateTitle"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
override func queryForTable() -> PFQuery {
var categoryCandidates = PFQuery(className: "CategoryCandidates")
categoryCandidates.whereKey("categoryID", equalTo: currentObject!)
return categoryCandidates
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> CandidateTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CandidateTableViewCell!
if cell == nil {
cell = CandidateTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
cell?.voteButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
// Extract values from the PFObject to display in the table cell
if let candidateTitle = object?["candidateTitle"] as? String {
cell?.textLabel?.text = candidateTitle
}
return cell
}
对于投票数,我在 Parse 上有一个单独的表(称为“CandidateVotes”),其中一行代表对“候选人”的每张投票。我想做的是对 CandidateVotes 表中具有指向给定“候选人”的指针的行进行计数。
但我不知道如何将其作为 queryForTable() 函数的一部分,以便将信息一起显示在表格 View 上。
有什么想法吗?
最佳答案
这是人们在设置这样的 ListView 时遇到的常见情况。我建议不要尝试提出返回所需数据的复杂查询,而是以一种可以使用最简单的查询获取此数据的方式对架构进行建模。
在这种情况下,您可以通过确保在 CategoryCandidates
表中跟踪候选人投票数据来实现此目的。然后,您的 cellForRow[...]
方法将能够从 key 获取此信息:
if let candidateVotesTotal = object?["candidateVotesTotal"] as? Number {
cell?.someTextLabel?.text = candidateVotesTotal
}
您可以通过在 CandidateVotes
类上使用 After Cloud 函数来确保“candidateVotesTotal”
跟踪此数据,该函数负责更新所有相关的 CategoryCandidates
每当记录新投票时都会对象。
关于swift - 如何使用 Swift 在 TableViewController 中包含不是主查询表的 Parse 类的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32322693/