我正在尝试从我的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
}
}
答案 0 :(得分:1)
您必须设置viewDidLoad
self.homeTableView.dataSource = self
答案 1 :(得分:0)
可能它没有用,因为你在二级线程上重新加载tablebview所以请你用下面的代码替换代码self.homeTableView.reloadData()
并尝试?
DispatchQueue.main.async {
self.homeTableView.reloadData()
}