2

How to access achieveTo() inside @main struct from CustomInternalView()?

@main
struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            CustomInternalView()
        }
    }

    public func achieveTo() {
        // Do stuff
    }
}


struct CustomInternalView: View {
    var body: some View {
         Text("Some")
    }
    .onDisappear {
        // How to call "achieveTo" from here????????????
    }
}

In UIKit it is like UIApplication.shared.windows.first!.rootViewController as! YourViewController, How about SwiftUI?

2
  • 2
    You don’t, work with state instead like using a State/Binding solution or an EnvironmentObject so that one view changes the state and the other reacts on the change (and calls achieveTo) Commented Aug 16, 2021 at 14:57
  • If an answer worked, can you click the green checkmark to accept it? Commented Aug 28, 2021 at 4:03

2 Answers 2

2

You can add a closure:

@main
struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            CustomInternalView {
                achieveTo() /// 2. Assign closure
            }
        }
    }

    public func achieveTo() {
        // Do stuff
    }
}
struct CustomInternalView: View {
    var callParentTask: (() -> Void) /// 1. Define closure
    
    var body: some View {
         Text("Some")
            .onDisappear(perform: callParentTask) /// 3. Call closure
    }
}

Note: Your onDisappear must be attached to a View inside the var body: some View {, not outside.

Sign up to request clarification or add additional context in comments.

Comments

2

Another simpler version of what @aheze answered:

import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        
        WindowGroup {
            
            CustomInternalView()
                .onDisappear() { achieveTo() }

        }
    }
}

func achieveTo() {
    // Do stuff
}

struct CustomInternalView: View {

    var body: some View {
         Text("Some")
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.