'How can I reproduce Picker's selection binding?

I'm building a custom view and I'm trying to manipulate the active state of its children.

I have this:

struct Menu<Content>: View where Content: View {
    
    @ViewBuilder var content: () -> Content
    
    var body: some View {
        content()
    }
}

struct ScreenView: View {
    var body: some View {
        Menu {
            Text("Home")
            Text("Settings")
            Text("Profile")
        }
    }
}

I would like to be able to pass a binding to the Menu view and based on that, to change the text color if the state is matching the actual text or id of the view. There is a Picker view example that does what I want to achieve. The Picker is managing the look and feel of the selected element. Am I wrong?

struct PickerViewExample: View {
    
    @State var selection: Int
    
    var body: some View {
        Picker(selection: $selection, label: Text("Picker"), content: {
            Text("1").tag(1)
            Text("2").tag(2)
        })
    }
}

I'd like to know if there is a way to ForEach somehow the content ViewBuilder property in order to manipulate subviews. I like the way Apple solved this using tags. Any alternative is welcome.



Solution 1:[1]

I think, this will help

struct ContentView: View {
    private var menuItem = ["Home", "Settings", "Profile"] 
    @State private var selectedMenu = "Home"

    var body: some View {
        VStack {
            Picker("Menu", selection: $selectedMenuIndex, content: {
                ForEach(menuItem, id: \.self, content: { title in 
                    Text(title) 
                })
            })
            Text("Selected menu: \(selectedMenu)")
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luke