我正在尝试从我的 firebase 数据库中创建一个 UITableView 显示数据,该数据库的结构如下
我需要第一个标签来显示商店的名称和商店的类型。当我打印数据库中的值时,它会显示商店列表和旁边的类型。但是,我发现很难将其复制到 UITableView 中。感谢您的帮助。这是我的代码:
import UIKit
import Firebase
struct shopStruct {
let shopName: String!
let shopType : String!
}
class HomeViewController: UIViewController, UITableViewDataSource , UITableViewDelegate {
@IBOutlet weak var homeTableView: UITableView!
var databaseRef: DatabaseReference!
var shops = [shopStruct]()
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = Database.database().reference()
databaseRef.child("shops").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let valueDictionary = snapshot.value as? [AnyHashable:String]
{
let shopName = valueDictionary["name"]
let shopType = valueDictionary["type"]
self.shops.insert(shopStruct(shopName: shopName, shopType: shopType), at: 0)
self.homeTableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let label1 = cell.viewWithTag(1) as! UILabel
label1.text = shops[indexPath.row].shopName
let label2 = cell.viewWithTag(2) as! UILabel
label2.text = shops[indexPath.row].shopType
return cell
}
}
最佳答案
你必须在viewDidLoad
中设置
self.homeTableView.dataSource = self
关于ios - 在 UITableView 中显示 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842564/