17.9 C
London
Friday, September 6, 2024

ios – Identifiable Content material views inside SwiftUI View


My purpose is to make a part that can be constructed as SwiftUI Listing. This part has two circumstances: it accepts a bunch of views, and it permits you to choose an merchandise primarily based on Identifiable protocol.

Pseudocode that visualise the case:

struct MainView: View {

personal let record: [UUID] = [...]
@State personal var choice: UUID?

var physique: some View {
   PagingView($choice) {
      ForEach(record) {
         RowItemView(mannequin: $0)
      }
   }
}

PagingView has initialiser that takes these two parameters:

struct PagingView<Content material>: View the place Content material: View {

   personal let content material: Content material
   @Binding personal var choice: UUID?

   init(_ choice: Binding<UUID?>, @ViewBuiled content material: @escaping () -> Content material) { [...] }

   var physique: some View {
      HStack {
         content material
      }
   }
}

The case is that inside PagingView I need to make some calculations primarily based on the view indexes and ids. Integer index is required to calculate offset place however, as choice, I’m passing id that’s UUID.

So the query is easy methods to get details about subviews offered by the ViewBuilder closure?

I had two options. First one changed Content material with [Content]:

struct PagingView<Content material>: View the place Content material: View {

   personal let content material: [Content]
   @Binding personal var choice: UUID?

   init(_ choice: Binding<UUID?>, @ViewBuiled content material: @escaping () -> [Content]) { [...] }

   var physique: some View {
      HStack {
         ForEach(content material.enumerated()) { index, merchandise in
            //save someplace a pair of phisical Int index with Identifiable peoperty.
            retailer(merchandise.id, for: index)

            return merchandise
         }
      }
   }
}

Sadly, it doesn’t work. This strategy prevents ForEach from getting used within the father or mother part. Really, it solves the issue in a really slender scope.

Second strategy added further @Binding to trace index and choice concurrently however then I’ve to synchronise these two values by onChange modifier.

Total, I didn’t resolve this downside for any explicit case.

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here