Skip to content

Instantly share code, notes, and snippets.

@zntfdr
Created June 28, 2020 10:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zntfdr/44b034bd03201ac6d0cfb71049d233fc to your computer and use it in GitHub Desktop.
Save zntfdr/44b034bd03201ac6d0cfb71049d233fc to your computer and use it in GitHub Desktop.
// 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