gpt4 book ai didi

SwiftUI ListView 没有访问 ForEach 循环

转载 作者:行者123 更新时间:2023-12-05 08:04:31 25 4
gpt4 key购买 nike

我正在使用 SwiftUI(我是新手)和 Firebase 使用 Swift 做一个项目。

我想根据从 Firebase 检索并存储在字典数组中的数据在 List View 上显示信息,这很好用,因为我可以在列表中显示我想看到的信息控制台中的单元格,但 Swift 未访问我正在读取数组数据的 ForEach 循环。

我尝试过的:

  1. id:\.self 添加到 ForEach 循环。
  2. 使 CourseInfo 结构符合 Hashable 协议(protocol)。

然后我发现其实并没有进入ForEach循环。

我会在下面留下我的代码。

谢谢。

Course.swift

import Foundation
import FirebaseAuth
import FirebaseFirestore

struct CourseInfo:Identifiable {
let id = UUID()
let courseName: String
let totalStudents: Int
let courseID: String
}

class Course: ObservableObject {
let user = Auth.auth().currentUser
let db = Firestore.firestore()

@Published var courses = [CourseInfo]()

func retreiveData() {
// Check if the user is signed in.
if user != nil {
// if user is signed in --> retreive all of the user's courses and info.
db.collection("courses").getDocuments() { [self] (querySnapshot, error) in
// Check for errors.
if let error = error {
print(error.localizedDescription)
}
else { // if there are not errors.
for course in querySnapshot!.documents {
let courseInfo = course.data()
manageData(courseInfo)
}
}
}
}
}// end retreiveData()

private func manageData(_ courseInfo: [String : Any]) {
var courseName: String = ""
var students: [Any] = []
var courseID: String = ""

for (key, value) in courseInfo {
if key == "Teacher" && value as! String == user!.uid {
for (key, value) in courseInfo {
if key == "Course Name" {
courseName = value as! String
}
else if key == "Course ID" {
courseID = value as! String
}
else if key == "Students"{
students = value as! Array<Any>
}
}
self.courses.append(CourseInfo(courseName: courseName, totalStudents: students.count, courseID: courseID))
}
}

} // end manageData()
}

CourseListView.swift

import SwiftUI

struct CourseListView: View {
var thaCourse:[CourseInfo] = Course().courses

var body: some View {
List {
ForEach(thaCourse) { course in
CourseCell(course: course)
}
}
}
}

struct CourseCell: View {
var course: CourseInfo

var body: some View {
VStack(alignment:.leading, spacing: 3) {

Text(course.courseName)
.font(.title2)
.fontWeight(.semibold)
.lineLimit(2)
.minimumScaleFactor(0.5)

Text("Total de alumnos: \(course.totalStudents)")

Text("ID: \(course.courseID)")
}
}
}

最佳答案

您需要在 View 中将Course 类声明为@StateObject(或@ObservedObject)属性,然后通过那个属性(property)。您还需要获取您的数据,这里我使用 onAppear

在 View 出现时执行此操作
@StateObject var course: Course = Course()

var body: some View {
List {
ForEach(course.courses) { course in
CourseCell(course: course)
}
}
.onAppear {
course.retreiveData()
}
}

关于SwiftUI ListView 没有访问 ForEach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68369298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com