ViewInspector icon indicating copy to clipboard operation
ViewInspector copied to clipboard

Question: How to traverse child inside Custom View with generic ViewBuilder

Open javalnanda opened this issue 2 years ago • 1 comments

Hi, I was trying to use this library and had few queries:

  1. Does all the custom view in the hierarchy need to confirm to Inspectable to find the child view or just the root parent view is enough to confirm to Inspectable?
  2. How can we traverse through CustomView with generic params? And what if the argument passed to them are private views?

For e.g: I have this View:

var body: some View {
        ZStack {
            ScreenScaffold(topBar: {
                TopBarSection(
                   //
                )
            }, content: {
                ContentSection(
                   //
                )
            }, bottomBar: {
                BottomBarSection(
                    //
                )
            })
         }  
  } 

Here ScreenScaffold is as below:

public struct ScreenScaffold<TopBar: View, Content: View, BottomBar: View>: View {}

And the ContentSection is private since it only serves to that specific ContentView. I want to find the buttons inside the ContentSection.

I am unable to find way to extract ScreenScaffold using: let scaffold = try sut.find(ScreenScaffold<AnyView, AnyView, AnyView>.self)

javalnanda avatar Jun 24 '22 11:06 javalnanda

Hey, my apologies for the late response.

Searching for a view with generic parameters requires you to specify all the generic parameters, which is inconvenient. You can work around this by searching for a child view inside those views and then calling parent. The approach is described in the guide. In your example, you can search for TopBarSection, for example: let scaffold = try sut.find(TopBarSection.self).parent() And yes, all your custom views, including TopBarSection, should be extended as Inspectable

nalexn avatar Sep 10 '22 21:09 nalexn

  1. Does all the custom view in the hierarchy need to confirm to Inspectable to find the child view or just the root parent view is enough to confirm to Inspectable?

In the current version conformance to Inspectable is no longer a requirement. The library now unwraps any custom views without conformance.

  1. How can we traverse through CustomView with generic params? And what if the argument passed to them are private views?

My initial answer above was not accurate - when searching for views with generic parameters you don't need to specify the correct generic type - you can use any that satisfies the type constraints. For example, if the generic parameter is just a View, then you can provide EmptyView, it should work.

nalexn avatar Jan 07 '23 14:01 nalexn