SwiftUI 嵌套 ForEach 应该只用于 *constant* 数据
Posted
技术标签:
【中文标题】SwiftUI 嵌套 ForEach 应该只用于 *constant* 数据【英文标题】:SwiftUI Nested ForEach should only be used for *constant* data 【发布时间】:2020-05-13 21:19:02 【问题描述】:我创建了一个带有嵌套 ForEach 循环的视图,我在日志中收到以下错误:
> count (2) != its initial count (1). `ForEach(_:content:)` should only
> be used for *constant* data. Instead conform data to `Identifiable` or
> use `ForEach(_:id:content:)` and provide an explicit `id`!
我已经使结构符合可识别的,这似乎无法解决错误。
我该如何解决这个错误?
import SwiftUI
struct LessonStruct: Identifiable
var id: Int
var name: String
var questions: [QuestionStruct]
struct QuestionStruct: Identifiable
var id: Int
var type: QuestionType
var description: String
var questionId: Int
class LessonsObject: ObservableObject
@Published var Array = [LessonStruct]()
@Published var selectedLesson: Int?
struct CreateLessonList: View
@EnvironmentObject var lesson: LessonsObject
@Binding var showingActionSheet: Bool
var rowNumber:Int = 0
var body: some View
VStack
ForEach(self.lesson.Array) each in
VStack(spacing: 0)
HStack()
TextField("Lesson \(each.id) - click to change name", text: self.$lesson.Array[each.id-1].name).font(.custom("Proxima Nova Alt Bold", size: 20)).foregroundColor(Color.white).padding(.leading, 10)
Spacer()
Image("PlusIcon").resizable().frame(width: 20, height: 20).padding(.trailing, 10).onTapGesture
self.lesson.selectedLesson = each.id - 1
self.showingActionSheet = true
.frame( height: 40).background(Color.init("Orange"))
if(self.lesson.Array[each.id - 1].questions.count == 0)
VStack
Text("Click the '+' icon to add a question.").font(.custom("Proxima Nova Alt Thin", size: 15))
.frame(height: 70)
else
ForEach(self.lesson.Array[each.id - 1].questions.indices) i in
if(self.lesson.Array[each.id - 1].questions[i].type == .Translation)
Group
HStack
Image("TranslationIcon").resizable().frame(width: 50, height:65)
Text(self.lesson.Array[each.id - 1].questions[i].description)
Spacer()
.padding(20)
.background(Color.init("White"))
【问题讨论】:
【参考方案1】:使用内部 ForEach 如下
ForEach(self.lesson.Array[each.id - 1].questions) question in
if(question.type == .Translation)
Group
HStack
Image("TranslationIcon").resizable().frame(width: 50, height:65)
Text(question.description)
Spacer()
.padding(20)
并检查您的 LessonStruct.id
构造逻辑,因为引用 [.id - 1]
看起来容易出错。
【讨论】:
以上是关于SwiftUI 嵌套 ForEach 应该只用于 *constant* 数据的主要内容,如果未能解决你的问题,请参考以下文章
无法让 ForEach 循环在 SwiftUI 中使用嵌套的 JSON 数据运行 [关闭]
[SwiftUI]:ForEach 不适用于字典数组、带数组的字典