【发布时间】:2021-07-08 14:07:52
【问题描述】:
我正在尝试创建一个弹出菜单,类似于我们在 SwiftUI 中的 .menu() 修饰符。我设法创建了修饰符,它工作正常。
问题:我遇到的问题是,当菜单显示时,我无法将覆盖扩展到整个屏幕。这是我尝试覆盖它时得到的结果(以蓝色显示)
问题的原因是我有一个 TabView,它被包裹在父 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))
}
}
【问题讨论】: