SwiftUI 添加覆盖到整个屏幕

Sid*_*ria 7 ios swift swiftui

我正在尝试创建一个弹出菜单,类似于.menu()我们在 SwiftUI 中的修改器。我设法创建了修改器并且它工作正常。

问题:我遇到的问题是,当显示菜单时,我无法将覆盖层扩展到整个屏幕。这是我尝试覆盖它时得到的结果(以蓝色显示)

问题的原因是我有一个TabViewwhich 包裹在parent 中NavigationView

在此输入图像描述

菜单修改器:这是我创建的用于显示弹出菜单的修改器。

import SwiftUI

struct PopupMenu<MenuContent: View>: ViewModifier {
    
    let menuContent: MenuContent
    @Binding var isPresented: Bool
    
    // Number crunching to limit menu size to 2/3rd of the screen
    private let paddingRatio: CGFloat = 0.33
    private let screenWidth = UIScreen.main.bounds.width
    
    init(isPresented: Binding<Bool>, @ViewBuilder content: () -> MenuContent) {
        _isPresented = isPresented
        menuContent = content()
    }
    
    func body(content: Content) -> some View {
        ZStack {
            // The content to show menu on
            content
            if isPresented {
                ZStack {
                    // Overlay to hide background - blue color is just to accentuate the issue
                    Color.blue
                        .onTapGesture {
                            isPresented.toggle()
                        }
                    // Actual menu rectangle
                    VStack {
                        HStack() {
                            Spacer(minLength: paddingRatio * screenWidth)
                            menuContent
                                .padding(regularPadding)
                                .background(
                                    RoundedRectangle(cornerRadius: regularCorner)
                                        .foregroundColor(.white)
                                        .shadow(color: darkGray.opacity(0.3), radius: 24, x: -4, y: 12)
                                )
                        }
                        Spacer()
                    }
                    .padding(.trailing, regularPadding)
                    .padding(.top, 2)
                }
            }
        }
    }
}

extension View {
    func popupMenu<MenuContent: View>(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> MenuContent) -> some View {
        self.modifier(PopupMenu(isPresented: isPresented, content: content))
    }
}
Run Code Online (Sandbox Code Playgroud)

Vis*_*kse 5

所以很明显你有一个NavigationView. 因此在这种情况下,请使用.overlay(popupMenu())将菜单覆盖在现有菜单上NavigationView

例如,

NavigationView {
    //Some content
}
.overlay(popup(_,_))

Run Code Online (Sandbox Code Playgroud)

在您的popOver视图中,确保将添加.ignoresSafeArea()Color视图中,如下所示

Color.blue
   .ignoresSafeArea()
   .onTapGesture {
       isPresented.toggle()
    }

Run Code Online (Sandbox Code Playgroud)