简体   繁体   中英

How to render a parent view in a child view in SwiftUI?

I am working on a mini iOS Project where my content view renders a custom map view on Content View (Root View).

What I would like to achieve is that in one of children view, which can be reached through a navigation link, I would like to display portion of the map view in the Content View without re-initializing a new map view. It is a 3d map (kind of heavy and expensive) so that it is not a good idea to re-initialize in the child view.

Is what I am trying to achieve possible in SwiftUI?

struct ContentView : View {

   public var myMapViewObj = myMapView()


    var body: some View {
    NavigationView{
        ZStack{
            myMapViewObj
            // Something like this
            NavigationLink(destination: someChildView(fromParentView: myMapViewObj))       
        }
    }
    }
}


struct someChildView: View {
    public var fromParentView : View
    var body: some View {
        VStack {
            myMapViewObj       // <- from ContentView
                .frame(height: UIScreen.main.bounds.height * 0.5)
            SomeOtherView()
        }
    }
}

Any opinion will be appreciated. Thanks

If your myMapViewObj is View type then you can use it with view constraint.

struct SomeChildView<Content: View>: View { //<--Here
    public var fromParentView : Content //<--Here
    var body: some View {
        VStack {
            myMapViewObj       // <- from ContentView
                .frame(height: UIScreen.main.bounds.height * 0.5)
            SomeOtherView()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM