【发布时间】:2021-04-12 19:06:46
【问题描述】:
我希望我能清楚地解释我的问题。
我想通过切换从列表中选择一些课程,但无论我尝试过什么都没有用。
我该怎么办?
感谢您的宝贵时间。 最好的, 穆拉特
struct SubjectCardsView: View {
// MARK: - Properties
@State var courses: [Course] = Bundle.main.decode("courses.json")
@State private var toggle: Bool = false
// MARK: - Body
var body: some View {
NavigationView {
List {
ForEach(courses) { course in
Section(header: Text(course.title).font(.system(size: 15, weight: .medium, design: .rounded)).foregroundColor(.blue)) {
ForEach(course.courseName, id: \.name) { item in
Toggle(isOn: $toggle, label: {
Text(item.name)
})
}
}
}
}
.listStyle(InsetGroupedListStyle())
.navigationBarTitle("Choose your subject", displayMode: .inline).font(.system(size: 16, weight: .medium, design: .rounded))
.navigationBarItems(leading: Button(action: {
}, label: {
Text("Cancel")
}), trailing: Button(action: {
}, label: {
Text("Save")
}))
} // NavigationView
}
}
课程部分!
import Foundation
import SwiftUI
struct Course: Codable, Identifiable {
var id: Int
var title: String
var subjectCount: String
var courseName: [Content]
var isToggled = false
private var imageName: String
var image: Image {
Image(imageName)
}
enum LessonSegment: String, CaseIterable, Identifiable {
case overview
case resources
var id: String { self.rawValue }
}
enum CodingKeys: String, CodingKey {
case id
case title
case subjectCount
case imageName
case courseName
}
}
struct Content: Codable {
var id: Int
var name: String
var content: String
var assessment: String
var notify: String
}
【问题讨论】:
-
你能附上
Course的代码吗? -
是的。我编辑了原始消息。
-
所以你想切换是否每个
Content被选中?Content上是否有某个属性应该响应切换?看起来你在Course上有一个isToggled,但你的Toggle控件在ForEach下courseName所以有点不清楚。其次,您是坚持使用Intid 还是可以使用更独特的东西,例如 UUID? -
每个 courseName 都有一个切换开关,因此我可以了解选择了哪个。选择后,将在内容视图中保存和过滤。我尝试使用 UUID 和 Int id,但它们不起作用。
标签: swift foreach swiftui toggle