[在一些视频的帮助下,我能够将Firestore数据解析为一个数组数组,但是现在我在弄清楚如何使用此数据填充表格视图时遇到了一些麻烦。想法是将“ dow”字段用于“部分”,将“ workouts”字段用于“行”。
如果我打印数组的第一个索引,这是我得到的输出...
[Days(dow: "Tuesday", workouts: [Effortflex.Workouts(workout: "Back")]), ..., ...]
我觉得我在这里错过了一步。有人可以帮我吗?
self.loadData { (Bool) in
if Bool == true {
print(self.dataArray[0])
self.dayCount = self.dataArray.count
}
}
struct Workouts {
var workout : String
}
struct Days {
var dow : String
var workouts : [Workouts]
var dictionary: [String : Any] {
return ["dow" : dow]
}
}
extension Days {
init?(dictionary: [String : Any], workouts : [Workouts]) {
guard let dow = dictionary["dow"] as? String else { return nil }
self.init(dow: dow, workouts: workouts)
}
}
//MARK: - Load Data
func loadData(completion: @escaping (Bool) -> ()){
let group = DispatchGroup()
self.rootCollection.getDocuments (completion: { (snapshot, err) in
if let err = err
{
print("Error getting documents: \(err.localizedDescription)");
}
else {
guard let dayDocument = snapshot?.documents else { return }
for day in dayDocument {
group.enter()
self.rootCollection.document(day.documentID).collection("Workouts").getDocuments { (snapshot, err) in
var workouts = [Workouts]()
guard let workoutDocument = snapshot?.documents else { return }
for workout in workoutDocument {
let workoutString = workout.data()["workout"] as! String
let newWorkout = Workouts(workout: workoutString)
workouts.append(newWorkout)
}
let dayTitle = day.data()["dow"] as! String
let newDay = Days(dow: dayTitle, workouts: workouts)
self.dataArray.append(newDay)
group.leave()
}
}
}
group.notify(queue: .main){
completion(true)
}
})
}
我举了一个例子,您可以以此为基础来使用您的结构。
将数组放入列表中,并保留在类的范围内,以便tableView的方法可以访问它。您可以进行如下转换:
let dataList = dataArray.flatMap{$0}
然后使用数据显示在tableView上>
func numberOfSections(in tableView: UITableView) -> Int {
dataList.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList[section].workouts.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataList[section].dow
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "testcell", for: indexPath)
cell.textLabel?.text = dataList[indexPath.section].workouts[indexPath.row].workout
return cell
}