Hi, I’m trying to implement a custom horiztonal Picker using the newly introduced API on ForEach like the following:
struct ScopeBar<SelectionValue: Hashable, Content: View>: View { // MARK: Initializers @Binding private var selection: SelectionValue @ViewBuilder private var content: () -> Content public init(selection: Binding<SelectionValue>, @ViewBuilder content: @escaping () -> Content) { _selection = selection self.content = content } // MARK: Content var body: some View { ScrollView(.horizontal) { LazyHStack { ForEach(subviews: content()) { subview in Button { // selection = subview.id as! SelectionValue } label: { subview } .tag(subview.id) } } } } }
The following implementation is what I’m trying to achieve for the custom container usage:
struct MyOtherView: View { enum SomeScopes: String, CaseIterable, Hashable { case first case second case third case fourth case fifth } @State private var selection: SomeScopes = .first var body: some View { ScopeBar(selection: $selection) { ForEach(SomeScopes.allCases, id: \.rawValue) { scope in Text(scope.rawValue) } } } }
I’m having some trouble figuring out two things:
- How can I make my
SelectionValue
equal to theSubview.ID
so that my selection behaves internally like aPicker
would? - Say I wanted to add an
Image(…)
in addition to theText(scope.rawValue)
, how would I do it in order for the Button { … } label: { … } to use both views, and not each separately…?