SwiftUI ListView 没有访问 ForEach 循环
Posted
技术标签:
【中文标题】SwiftUI ListView 没有访问 ForEach 循环【英文标题】:SwiftUI ListView is not accessing the ForEach loop 【发布时间】:2021-07-13 21:04:32 【问题描述】:我正在使用 SwiftUI(我是新的)和 Firebase 使用 Swift 做一个项目。
我想从我从 Firebase 检索并存储在字典数组中的数据中显示 List View
的信息,这工作正常,因为我可以在控制台的列表单元格中显示我想看到的信息,但 Swift没有访问我正在读取数组数据的 ForEach 循环。
我尝试过的:
-
将
id: \.self
添加到 ForEach 循环中。
使 CourseInfo
结构符合 Hashable 协议。
然后我意识到它实际上并没有进入 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)")
【问题讨论】:
【参考方案1】:您需要在视图中将Course
类声明为@StateObject
(或@ObservedObject
)属性,然后通过该属性访问数组。你还需要获取你的数据,这里我在视图出现时使用onAppear
@StateObject var course: Course = Course()
var body: some View
List
ForEach(course.courses) course in
CourseCell(course: course)
.onAppear
course.retreiveData()
【讨论】:
以上是关于SwiftUI ListView 没有访问 ForEach 循环的主要内容,如果未能解决你的问题,请参考以下文章
过滤列表项后,ListView 中的 SwiftUI TextField 变为空白
SwiftUI for MacOS 窗口,带圆角,不带标题栏