-
-
Save zntfdr/44b034bd03201ac6d0cfb71049d233fc to your computer and use it in GitHub Desktop.
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
// 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