🐙

SwiftUI hidden tip - _VariadicViewを使ってtagをindexに応じて割り当てる

2023/05/31に公開
fileprivate struct TagAssignment<Content: View>: View {

  let tree: _VariadicView.Tree<VariadicViewProxy, Content>

  init(@ViewBuilder content: () -> Content) {
    self.tree = _VariadicView.Tree(VariadicViewProxy(), content: content)
  }

  var body: some View {
    tree
  }

  struct VariadicViewProxy: _VariadicView_MultiViewRoot {
    @ViewBuilder
    func body(children: _VariadicView.Children) -> some View {
      ForEach(children.indexed(), id: \.element.id) { a in
        a.element
          .tag(a.index)
      }
    }
  }

}
    TabView(selection: $currentIndex) {
      TagAssignment {
	Self.makeCarouselItem()
	Self.makeCarouselItem()
	Self.makeCarouselItem()
      }
    }
      .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))

https://muukii.notion.site/SwiftUI-under-the-Hood-Variadic-Views-df6cc157194243c18e3b3cee51aeebf2

Discussion