Swift 3将Firebase数据写入TableView

问题描述 投票:0回答:2

我从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
    }
}
ios swift firebase firebase-realtime-database
2个回答
0
投票

你是压倒错误的方法

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

并在Interface Builder中设计单元格样式,并在cellForRowAt中使用此方法

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

0
投票

根据您的要求,获取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
}
© www.soinside.com 2019 - 2024. All rights reserved.