How to make ContentView_Previews working without changing the structure of the app?
import SwiftUI
@main
struct testApp: App {
@State var function:(() -> Void)? = {}
var body: some Scene {
WindowGroup {
ContentView(myFunction: $function)
}
}
}
struct ContentView: View {
@State var text: String = "Parent"
var isNavigationViewAvailable = true
@Binding var myFunction: (() -> Void)?
func function() {
print("This view is \(text)")
}
var body: some View {
VStack {
if isNavigationViewAvailable {
Button(action: {
if myFunction != nil {
myFunction!()
}
}, label: {
Text("Button")
})
}
if isNavigationViewAvailable {
NavigationView {
List {
NavigationLink("Child1") {
ContentView(text: "Child1", isNavigationViewAvailable: false, myFunction: $myFunction)
}
NavigationLink("Child2") {
ContentView(text: "Child2", isNavigationViewAvailable: false, myFunction: $myFunction)
}
NavigationLink("Child3") {
ContentView(text: "Child3", isNavigationViewAvailable: false, myFunction: $myFunction)
}
}
}
}
}.onAppear {
if !isNavigationViewAvailable {
myFunction = {
function()
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
@State var function:(() -> Void)? = {}
static var previews: some View {
ContentView(myFunction: $function)
}
}
I want to keep this structure, so that one object should have child objects of the same class. And have ability to run the functions of its child objects. The question is connected with my previous question, but I found the better way I think to implement this.
CodePudding user response:
You can use it like this
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(myFunction: .constant({}))
}
}