ios - 从 Firebase 检索数据到 TableView

标签 ios swift uitableview firebase firebase-realtime-database

在一个 View 中,我的用户在输入字段中键入了一些文本,我将其保存为 ticket(此过程没有问题并已成功添加到我的数据库 ).

我希望所有这些 ticket 值都显示在 tableView 中,其中每个单元格都包含一个 ticket。我一直在玩,这是我能做到的,但仍然不够。

 import UIKit
 import Firebase

 class TestTableViewController: UITableViewController {

let cellNavn = "cellNavn"

  var holes: [FIRDataSnapshot]! = []


let CoursesRef = FIRDatabase.database().reference().child("Ticketcontainer")


override func viewDidLoad() {
    super.viewDidLoad()

    CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
        self.holes = snapshot.childSnapshotForPath("tickets").children.allObjects as! [FIRDataSnapshot]
    })

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(handleCancel))

    tableView.registerClass(UserCell.self, forCellReuseIdentifier: cellNavn)


}


func handleCancel() {
    dismissViewControllerAnimated(true, completion: nil)
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(cellNavn, forIndexPath: indexPath) as! UserCell                       
    cell.textLabel?.text = self.holes[indexPath.row].value as? String

    return cell

}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 72
}    

}

最佳答案

首先,在 numberOfRowsInSection 方法中,您需要返回数组的计数,而不是一些静态值。

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

在闭包中初始化数组后,您需要重新加载 tableView

CoursesRef.observeEventType(.ChildAdded, withBlock: { snapshot in
    self.holes = snapshot.childSnapshotForPath("tickets").children.allObjects as! [FIRDataSnapshot]
    self.tableView.reloadData()
})

关于ios - 从 Firebase 检索数据到 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775232/

相关文章:

ios - didRegisterForRemoteNotificationsWithDeviceToken 在 swift 5 中不起作用

ios - 将 Objective-C block 转换为 Swift

ios - 未在 swift 中调用的协议(protocol)方法

ios - 如何在 TableView 中调整 cell.imageView 的大小并在 Swift 中应用 tintColor

ios - 从 TableView Controller 引用特定的 TableView 单元格

ios比较来自json的 bool 值

ios - 如何在ios中动态生成多页pdf时处理分页

ios - 在 firestore 中添加新 key 时应用程序崩溃

ios - 跨数据库更新用户名

ios - 静态 UITableView 中的节标题大小不均匀