Swiftui Identifiable Foreach 可以仅循环 select 前 5 个项目吗

Can a Swiftui Identifiable Foreach loop select only the first 5 items

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

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)
   }
}

谢谢

这里有一个简单的方法供您参考:

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))

        }

    }
    
}

你可以尝试这样的事情:

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

使用@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,瞧,结果都很好。