简体   繁体   English

无法将从Firebase检索到的数组项输出到Swift中的UITableView

[英]Unable To Output Array Items Retrieved From Firebase To UITableView In Swift

If I use the static array that has the basic strings in it, I can render those out to the UITableView, BUT when I build my "jokes" array and use that for the datasource for the table cells, I just get empty list in UI. 如果我使用包含基本字符串的静态数组,则可以在构建“笑话”数组并将其用于表单元格的数据源时将其呈现给UITableView,但是,我只是在UI中获得了空列表。 Rows output, but no data. 行输出,但没有数据。

I'm sure it's something simple, still new to Swift (.net background). 我敢肯定这是简单的事情,对于Swift(.net背景)还是一个新东西。

Why are the "jokes" array items not displaying in the tableViewCell? 为什么“笑话”数组项没有显示在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

}
}

All your code is correct just make sure you add tableView.reloadData() 您所有的代码都是正确的,只需确保添加tableView.reloadData()

After this line 在这行之后

print(myJokeCollection.postUser)
tableView.reloadData()

Why is this needed? 为什么需要这个?

This is needed to reload the tableView after you have added new data, the tableView is automatically loaded when the view launches but when you add new data you must call this to tell the tableView, "Oh, I've got new data! Time to reload!" 添加新数据后需要重新加载tableView,在视图启动时会自动加载tableView,但是当添加新数据时,您必须调用此方法以告知tableView:“哦,我有新数据!重新加载!”

Though @OkiRules answer is correct i would like to correct one thing and that is do not reload data in loop it just increases processing time and keeps UI more busy. 尽管@OkiRules答案是正确的,但我想纠正一件事,即不要循环重新加载数据,它只会增加处理时间并使UI更加繁忙。 Reload data out of loop, Do it like below. 重新循环加载数据,如下所示。

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"

                    }
    tableView.reloadData()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM