在 ForEach SwiftUI 中随机播放
Shuffle inside a ForEach SwiftUI
如果做一个非常简单的 ForEach 循环,我可以使用 shuffle 参数来随机播放里面的东西。
链接如下:
var plays: [Play] = playData
var body: some View {
NavigationView {
ScrollView {
ForEach(plays.shuffled()) { item in
NavigationLink {
PlayDetailView(play: item)
} label: {
PlayCard(play: item)
.padding(.vertical, 7)
}
}
}
但是当我使用 Environment 对象并在循环内调用不同的东西时,我无法选择随机播放。
谁能给我指明正确的方向打乱以下循环的结果?
var body: some View {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 160), spacing: 15)]) {
ForEach(0..<modelData.stories.count, id: \.self) { item in
if modelData.stories[item].featured == true {
NavigationLink {
StoryDetails(story: modelData.stories[item])
} label: {
GeneralCard(story: modelData.stories[item])
}
}
}
}
}
这是模型数据:
struct Story: Hashable, Codable, Identifiable {
var id: Int
var title: String
var description: String
var featured: Bool
var paid: Bool
var featuredImage: String
var bigImage: String
var text: [String]
var category: Category
}
您正在创建一个封闭范围并对其进行迭代,按索引访问数据。这本身就不是一个好习惯。如果您遍历集合本身会更容易。
ForEach(modelData.stories.shuffled()) { story in
if story.featured == true {
NavigationLink {
StoryDetails(story: story)
} label: {
GeneralCard(story: story)
}
}
您不需要此处带有 id 的初始值设定项。您的 Story
项已符合 Identifiable
。
如果做一个非常简单的 ForEach 循环,我可以使用 shuffle 参数来随机播放里面的东西。
链接如下:
var plays: [Play] = playData
var body: some View {
NavigationView {
ScrollView {
ForEach(plays.shuffled()) { item in
NavigationLink {
PlayDetailView(play: item)
} label: {
PlayCard(play: item)
.padding(.vertical, 7)
}
}
}
但是当我使用 Environment 对象并在循环内调用不同的东西时,我无法选择随机播放。
谁能给我指明正确的方向打乱以下循环的结果?
var body: some View {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 160), spacing: 15)]) {
ForEach(0..<modelData.stories.count, id: \.self) { item in
if modelData.stories[item].featured == true {
NavigationLink {
StoryDetails(story: modelData.stories[item])
} label: {
GeneralCard(story: modelData.stories[item])
}
}
}
}
}
这是模型数据:
struct Story: Hashable, Codable, Identifiable {
var id: Int
var title: String
var description: String
var featured: Bool
var paid: Bool
var featuredImage: String
var bigImage: String
var text: [String]
var category: Category
}
您正在创建一个封闭范围并对其进行迭代,按索引访问数据。这本身就不是一个好习惯。如果您遍历集合本身会更容易。
ForEach(modelData.stories.shuffled()) { story in
if story.featured == true {
NavigationLink {
StoryDetails(story: story)
} label: {
GeneralCard(story: story)
}
}
您不需要此处带有 id 的初始值设定项。您的 Story
项已符合 Identifiable
。