Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created November 28, 2023 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/80f1a3637462014a48f3084c178c8872 to your computer and use it in GitHub Desktop.
Save shaps80/80f1a3637462014a48f3084c178c8872 to your computer and use it in GitHub Desktop.
Automatically adds Divider elements between views in this container.
import SwiftUI
public struct Divided<Content: View, Separator: View>: View {
var content: Content
var separator: Separator
public init(@ViewBuilder content: () -> Content, @ViewBuilder separator: () -> Separator) {
self.content = content()
self.separator = separator()
}
public var body: some View {
content.variadic { views in
ForEach(Array(views.enumerated()), id: \.offset) { offset, element in
element
if offset != views.count - 1 {
separator
}
}
}
}
}
public extension Divided where Separator == Divider {
init(@ViewBuilder content: () -> Content) {
self.content = content()
self.separator = Divider()
}
}
private extension View {
func variadic<R: View>(@ViewBuilder _ transform: @escaping (_VariadicView.Children) -> R) -> some View {
_VariadicView.Tree(Helper(transform: transform)) { self }
}
}
private struct Helper<R: View>: _VariadicView.MultiViewRoot {
var transform: (_VariadicView.Children) -> R
func body(children: _VariadicView.Children) -> some View {
transform(children)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment