1

I'm trying to understand how Apple extracts the individual views from ViewBuilder TupleViews. Specifically with things like List that support lazy loading of views.

I have managed to build a lazy loading UIViewRepresentable table view using reflection (done with some slight modifications to GeorgeElsham's ViewExtractor https://github.com/GeorgeElsham/ViewExtractor/pull/4/files). However, I'm still trying to find a way to do it without reflection.

A solution like this feels close to how Apple is probably handling it, given the 10 view limit they have on view builders:

https://stackoverflow.com/a/64426470/1877760

    init<V0: View, V1: View>(
        @ViewBuilder content: @escaping () -> TupleView<(V0, V1)>
    ) {
        let cv = content().value
        inputViews = [AnyView(cv.0), AnyView(cv.1)]
    }

    init<V0: View, V1: View, V2: View>(
        @ViewBuilder content: @escaping () -> TupleView<(V0, V1, V2)>) {
        let cv = content().value
        inputViews = [AnyView(cv.0), AnyView(cv.1), AnyView(cv.2)]
    }

    init<V0: View, V1: View, V2: View, V3: View>(
        @ViewBuilder content: @escaping () -> TupleView<(V0, V1, V2, V3)>) {
        let cv = content().value
        inputViews = [AnyView(cv.0), AnyView(cv.1), AnyView(cv.2), AnyView(cv.3)]
    }

...

The issue I've found with this sort of solution is that ForEach blocks are treated as single views, and so all of their content is put into a single row in the table view (and therefore also loaded all at once). I'm not too sure how to proceed without using reflection to see if a given view in a TupleView is a ForEach or not.

List can handle things like this, so I'm guessing Apple is drilling down recursively.

List {
    ForEach(0..<5) { index1 in
        ForEach(0..<2) { index2 in
            ForEach(0..<2) { index3 in
                Text("\(index1)\(index2)\(index3)")
            }
        }
    }
}

I guess to put a clear definition on the goal: Given a ViewBuilder with between 0-10 views inside of it (of which any or all can be ForEach views, of which can be nested), return an array of the views (with ForEach's content views expanded out).

Does anyone know how Apple does it?

user1877760
  • 263
  • 2
  • 9

0 Answers0