我的应用程序从 Firebase 数据库中检索数据,使用我的 CustomCell 将其放入 tableView 中,我的目标是当点击一个单元格时,我想要存储在该点击单元格中的标签中的字符串。
所以我现在已经尝试了几天,所提供的解决方案大多只适用于静态单元格,其中的内容不是动态加载的,就像它在这里一样。 我尝试过的选项:
- 使用数组存储内容,然后将它们与
indexPath
结合使用:事实证明这很困难,因为数组没有与 Firebase 正确同步,导致indexPath
中的顺序错误。我还没有找到保持数组同步的库,但普遍的共识似乎是我应该在使用 Firebase 时远离数组。 - 像建议的那样使用委托(delegate)或闭包 here :因为我使用 FirebaseUI 来填充我的单元格,所以我没有
cellForRowAtIndexPath
或dequeueReusableCellWithIdentifier
这两种方法,这也使解决方案变得困难。
我目前拥有的:
func getQuery() -> FIRDatabaseQuery {
let myTopPostsQuery = (ref.child("posts"))
return myTopPostsQuery
}
override func viewDidLoad() {
super.viewDidLoad()
self.ref = FIRDatabase.database().reference()
dataSource = FirebaseTableViewDataSource.init(query: getQuery(),prototypeReuseIdentifier: "Cellident", view: self.tableView)
dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
let customCell = cell as! CustomCellTableViewCell
let snap = obj as! FIRDataSnapshot
let childString = snap.value as! [String : AnyObject]
customCell.textLabel.text = String(childString)} // << This is what I need to access in didSelectRowAtIndexPath
}
tableView.dataSource = dataSource
tableView.delegate = self
}
我现在的问题是什么是最实用的方法,是否有我尚未考虑的解决方案?
最佳答案
在 didSelectRowAtIndexPath TableViewDelegate 方法中执行此操作
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let path: NSIndexPath = indexPath
let source = dataSource
let snapshot: FIRDataSnapshot = (source?.objectAtIndex(UInt(path.row)))! as! FIRDataSnapshot
let childString = snapshot.value as! String
}
关于swift - 在 didSelectRowAtIndexPath 中访问来自 Firebase 的 CustomCell 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951737/