Search code examples
iosswiftuikitswiftuiz-index

The z-index of SwiftUI View and UIKit View


The SwiftUI scroll view is hiding some area of a view presented from UIViewControllerRepresentable viewController.

enter image description here

Part of the SwiftUI code, The GoogleMapsView is the UIViewControllerRepresentable viewController.

struct ContentView: View {

var body: some View {
    ZStack(alignment: .top) {

        GoogleMapsView()

        VStack(alignment: .leading) {
            Text("Top Locations near you")

            ScrollView(.horizontal, showsIndicators: false) {
                HStack() {
                    ForEach(dataSource.topPlaces) { place in
                        PlaceCardView(placeImage: place.image, placeName: place.name, placeRating: place.rating, placeRatingTotal: place.ratingTotal, topPlace: place)
                    }
                }
                .padding(.horizontal, 10)
            }
            .background(Color.clear)
            .foregroundColor(.black)
            .frame(height: 200)
            .opacity(self.finishedFetching ? 1 : 0.1)
            .animation(.easeInOut(duration: 1.3))           
    }.edgesIgnoringSafeArea(.all)
}

The view I want to put on the top is from the GoogleMapView() which I put it on the "bottom" of the ZStack because I want that Scroll view to flow on the map. However the view show on the map when marker is tapped is cover up by the SwiftUI ScrollView

I tried to change their zIndex of the scrollView, zPosition of the pop up view or bringSubviewToFront etc. None of them work.


Solution

  • You need to inject local state via binding into `` and change it there on popup shown/hidden.

    Here is some pseudo code

    struct ContentView: View {
    
    @State private var isPopup = false
    
    var body: some View {
        ZStack(alignment: .top) {
    
            GoogleMapsView(isPopup: $isPopup)
    
            VStack(alignment: .leading) {
                Text("Top Locations near you")
    
                if !isPopup {
                   ScrollView(.horizontal, showsIndicators: false) {
                      // other code
                   }
                   // other code
                }
        }.edgesIgnoringSafeArea(.all)
    }
    
    struct GoogleMapsView : UIViewControllerRepresentable {
       @Binding isPopup: Bool
    
       // other code
    
       // make self.isPopup = true before popup and false after