一个Swiftui可识别的Foreach循环可以只选择前5个项目吗?



你好,我有一个项目,只需要显示前5个项目的循环超过30项,下面是我的代码

struct Introductions: Codable, Identifiable {
let id: String
let topIntros: String?
let image: String
let date: String
}
ForEach(introductions) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}

我尝试使用这种方法,但xcode崩溃崩溃后,我滚动过第五项

ForEach(introductions, id: .topIntros) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}

感谢

你可以尝试这样做:

if (introductions.count >= 5) {
ForEach(introductions.prefix(upTo: 5), id:.id) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}
}

这里有一个简单的方法:

struct ContentView: View {

@State private var array: [Int] = Array(100...130)
var body: some View {

if (array.count >= 5) {

ForEach(0...4, id:.self) { index in

Text(String(describing: array[index]))

}

}
}

}

给你另一种方法:

struct ContentView: View {

@State private var array: [Int] = Array(100...130)
var body: some View {

ForEach(array.dropLast(array.count - 5), id:.self) { item in

Text(String(describing: item))
}
}

}

使用@workingdog的评论,我能够修复它并在下面发布答案,以防万一它派上用场。

struct Introductions: Codable, Identifiable {
let id: String
let topIntros: String?
let image: String
let date: String
}
ForEach(introductions) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}

struct ContentView: View {
var body: some View {
VStack { 
if (introductions.count >= 5) {
ForEach(introductions.prefix(upTo: 5), id:.topIntros) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}
} else {
ForEach(introductions) { introduction in
NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
IntroductionsView(introduction: introduction)
}
}
}
}
}

}

使用。id打破了视图的层次结构,所以我使用了可选的。topintros,瞧,一切都很好。

相关内容

  • 没有找到相关文章

最新更新