0

你好我有一个项目只需要在超过 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)
   }
}

谢谢

4

3 回答 3

0

这里给你一个简单的方法:

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

        }

    }
    
}
于 2021-10-05T00:42:35.103 回答
0

你可以尝试这样的事情:

if (introductions.count >= 5) {
    ForEach(introductions.prefix(upTo: 5), id:\.id) { introduction in
       NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
          IntroductionsView(introduction: introduction)
       }
    }
}
于 2021-10-05T01:59:00.937 回答
0

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

于 2021-10-05T03:17:06.650 回答