如果我使用其中包含基本字符串的静态数组,我可以将它们渲染到 UITableView,但是当我构建我的“笑话”数组并将其用于表格单元格的数据源时,我只是变空了在 UI 中列出。行输出,但没有数据。
我确信它很简单,对 Swift(.net 背景)来说仍然是新的。
为什么“笑话”数组项没有显示在 tableViewCell 中?
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var dict : [String: AnyObject] = [:]
var jokes = [Jokes]()
private let myArray: NSArray = ["First","Second","Third"]
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
var ref = Database.database().reference()
ref.observe(.value, with: { (snapshot) in
for child in snapshot.children { //even though there is only 1 child
let snap = child as! DataSnapshot
// let dict = snap.value as? NSDictionary
self.dict = snap.value as! [String: AnyObject]
for (joke, item) in self.dict ?? [:] {
let myJokeCollection = Jokes(fromDict: item as! [String : AnyObject]); //This has object from Dictionary retrieved from firebase
self.jokes.append(myJokeCollection)
print(myJokeCollection) //This prints collection
print(myJokeCollection.postUser) // this prints the "post user"
}
}
})
//Below is intial example
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "JokeCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
// print("Value: \(myArray[indexPath.row])") <- THis works as it's declared at the top of class
print("Value: \(jokes[indexPath.row])") //THis prints nothing (of course)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jokes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JokeCell", for: indexPath as IndexPath)
//If I use reference to myArray below it prints those items, but not from mine "jokes"
cell.textLabel!.text = "\(jokes[indexPath.row])"
return cell
}
}
class Jokes {
var postUser: String?
var punchline: String?
var rating: Int?
var setup: String?
init(fromDict dict:[String: AnyObject]) {
self.postUser = dict["PostUser"] as? String
self.punchline = dict["Punchline"] as? String
self.rating = dict["Rating"] as? Int
self.setup = dict["Setup"] as? String
}
}
最佳答案
你所有的代码都是正确的,只要确保你添加了 tableView.reloadData()
在这一行之后
print(myJokeCollection.postUser)
tableView.reloadData()
为什么需要这个?
添加新数据后需要重新加载 tableView,当 View 启动时 tableView 会自动加载,但是当您添加新数据时,您必须调用它来告诉 tableView,“哦,我有新数据!是时候重新加载了!”
关于ios - 无法在 Swift 中将从 Firebase 检索到的数组项输出到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955410/