Created
November 28, 2023 12:17
-
-
Save shaps80/80f1a3637462014a48f3084c178c8872 to your computer and use it in GitHub Desktop.
Automatically adds Divider elements between views in this container.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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