Может ли цикл Swiftui Identifiable 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)
   }
}

Спасибо

3 ответа

Решение

вы можете попробовать что-то вроде этого:

      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 и вуаля, все получилось нормально.

Другие вопросы по тегам