簡體   English   中英

Swift 3將Firebase數據寫入TableView

[英]Swift 3 Writing Firebase Data to TableView

我正在從Firebase數據庫中獲取所有用戶ID。 當我執行該程序時,可以通過第26行的代碼在控制台上看到所有用戶ID的快照。但是該代碼未寫入表單元格。 我是通過教程完成的。 視頻一切都一樣。 但這對我不起作用問題出在哪里?

    class ChatInfo: UITableViewController {

    let cellId = "cellId"
    var users = [User] ()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Geri", style: .plain, target:self, action: #selector(handleCancel))
        fetchUser()
    }
    func handleCancel() {

        dismiss(animated: true, completion: nil)

    }
    func fetchUser() {

        Database.database().reference().child("locations").observe(.childAdded, with: {(snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let user = User()

                user.userId = dictionary["userId"] as! String
                print(user.userId) // IT PRINTS ALL USERS  TO CONSOLE
                self.users.append(user)

                DispatchQueue.main.async(execute: {
                 self.tableView.reloadData()
                })
            }

        } , withCancel: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return users.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)

        let user = users[indexPath.row]
        cell.detailTextLabel?.text = user.userId
        return cell
    }
}

您要覆蓋錯誤的方法

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count
}

並在Interface Builder中設計單元格樣式,並在cellForRowAt使用此方法

let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath)

根據您的要求,獲取tableview單元格記錄的實際方式是這樣的:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath)
    let user = users[indexPath.row]
    cell.detailTextLabel?.text = user.userId
    return cell
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM