Skip to content

Instantly share code, notes, and snippets.

@zntfdr

zntfdr/MyDisclosureGroup.swift Secret

Created Jun 28, 2020
Embed
What would you like to do?
// Final implementation of MyDisclosureGroup
// read more at https://www.fivestars.blog
import SwiftUI
struct MyDisclosureGroup<Label, Content>: View where Label: View, Content: View {
@State private var myIsExpanded: Bool = false
private var isExpanded: Binding<Bool>?
var content: () -> Content
var label: () -> Label
public init(isExpanded: Binding<Bool>, content: @escaping () -> Content, label: @escaping () -> Label) {
self.init(isExpanded: .some(isExpanded), content: content, label: label)
}
public init(content: @escaping () -> Content, label: @escaping () -> Label) {
self.init(isExpanded: nil, content: content, label: label)
}
private init(isExpanded: Binding<Bool>?, content: @escaping () -> Content, label: @escaping () -> Label) {
self.isExpanded = isExpanded
self.content = content
self.label = label
}
private struct OriginalDisclosureGroup<Label, Content>: View where Label: View, Content: View {
@Binding var isExpanded: Bool
var content: () -> Content
var label: () -> Label
@ViewBuilder
var body: some View {
Button(action: { isExpanded.toggle() }, label: label)
if isExpanded {
content()
}
}
}
var body: some View {
OriginalDisclosureGroup(
isExpanded: isExpanded ?? $myIsExpanded,
content: content,
label: label
)
}
}
struct ContentView: View {
@State var showingContent = true
@ViewBuilder
var body: some View {
// no binding
MyDisclosureGroup {
Text("Content")
} label: {
Text("Tap to show content")
}
.padding(.all, 20)
// binding
MyDisclosureGroup(isExpanded: $showingContent) {
Text("Content")
} label: {
Text("Tap to show content")
}
.padding(.all, 20)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.sizeThatFits)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.