我正在尝试从我在 firebase 中的数据创建一个数组,以便我可以将它作为标题加载到我的 tableview 中。当我将信息硬编码在代码中的数组中时,我了解如何将数据放入节标题中,但是当数据在 Firebase 中并且我想将其放入数组然后把它放在标题中。希望这是有道理的。
我的 Firebase 数据是
usclmainmenu
events
USCL Open House
date:
"September 31 2020"
info:
"Opening to new students"
place:
"USC Lancaster"
time:
"8 pm"
title:
"USCL Open House"
我从 firebase 获取数据的功能是:
private func getEventsFromFirebaseDB()
{
datref = Database.database().reference().child("events")
datref.observe(DataEventType.value, with: { [weak self] (snapshot) in
guard snapshot.childrenCount > 0 else { return }
var events: [EventsInfo] = []
for event in snapshot.children.allObjects as! [DataSnapshot]
{
let object = event.value as? [String: AnyObject]
let title = object?["title"]
let place = object?["place"]
let info = object?["info"]
let date = object?["date"]
let time = object?["time"]
let event = EventsInfo(title: title as! String, place: place as! String, info: info as! String, time: time as! String, date: date as! String)
events.append(event)
}
self?.eventsFetched(events)
self?.eventTableView.reloadData()
})
}
我的数据模型是:
class EventsInfo {
var title: String
var place: String
var info: String
var time: String
var date: String
init(title: String, place: String, info: String, time: String, date: String) {
self.title = title
self.place = place
self.info = info
self.time = time
self.date = date
}
}
这是我的数据源和委托方法的扩展
extension EventsTableViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int
{
sectionNames.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
sectionNames[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let char = sectionNames[section]
return events[char]!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = eventTableView.dequeueReusableCell(withIdentifier: "eventsCell") as! EventsTableViewCell
let char = sectionNames[indexPath.section]
let event = events[char]![indexPath.row]
cell.eventTitleLabel.text = event.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showEvent", sender: self)
}